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 function
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 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}")}
Explanation
In the above code:
-
Line 3: We create a new
HashSetobject with the nameset. We used thehashSetOf()method to create an emptyHashSet. -
Lines 6 to 9: We add four new elements
(1,2,3,4)to thesetusing theadd()method. -
Line 14: We use the
find()method with a predicate function. The predicate function returnstrueif the element is greater than 2. In our case, the elements3and4are greater than 2. Thefind()method returns the first element that is greater than2. -
Line 18: We use the
find()method with a predicate function. The predicate function returnstrueif the element is greater than 4. In our case, there is no element that is greater than4sonullis returned.