The find() method of HashSet can be used to get the first element that matches the given condition.
inline fun <T> Iterable<T>.find(
predicate: (T) -> Boolean
): T?
This method takes a predicate function
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.
The code below demonstrates how to use the find() method:
fun main() {//create a new HashSet which can have integer type as elementsvar set: HashSet<Int> = hashSetOf<Int>()// add four entriesset.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 2var firstValueGreaterThan2 = set.find( { it > 2 } )println("First value greater than 2 : ${firstValueGreaterThan2}")//use find method to get the. first element greater than 4var firstValueGreaterThan4 = set.find( { it > 4 } )println("First value greater than 4 : ${firstValueGreaterThan4}")}
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.