How to use the find() method of the HashSet in Kotlin

Overview

The find() method of HashSet can be used to get the first element that matches the given condition.

Syntax

inline fun <T> Iterable<T>.find(
    predicate: (T) -> Boolean
): T?

Parameter

This method takes a predicate functionPredicate is a functional interface that takes one argument and returns either true or false based on the condition defined. as an argument.

Return value

This method returns the first element that matches the given predicate. If no element in the Set matches the given condition then null is returned.

Example

The code below demonstrates how to use the find() method:

fun main() {
//create a new HashSet which can have integer type as elements
var set: HashSet<Int> = hashSetOf<Int>()
// add four entries
set.add(1)
set.add(2)
set.add(3)
set.add(4)
println("\nThe set is : $set")
//use find method to get the. first element greater than 2
var firstValueGreaterThan2 = set.find( { it > 2 } )
println("First value greater than 2 : ${firstValueGreaterThan2}")
//use find method to get the. first element greater than 4
var firstValueGreaterThan4 = set.find( { it > 4 } )
println("First value greater than 4 : ${firstValueGreaterThan4}")
}

Explanation

In the above code:

  • Line 3: We create a new HashSet object with the name set. We used the hashSetOf() method to create an empty HashSet.

  • Lines 6 to 9: We add four new elements(1,2,3,4) to the set using the add() method.

  • Line 14: We use the find() method with a predicate function. The predicate function returns true if the element is greater than 2. In our case, the elements 3 and 4 are greater than 2. The find() method returns the first element that is greater than 2.

  • Line 18: We use the find() method with a predicate function. The predicate function returns true if the element is greater than 4. In our case, there is no element that is greater than 4 so null is returned.

Free Resources