Determine if an element is present in a Set in Kotlin
This article explores different ways to determine if an element is present in a Kotlin Set.
1. Using contains() function
In Kotlin, the recommended way to check if an element is present in a Set is using the contains() function. It returns a boolean value true if the set contains the specified element, false otherwise.
|
1 2 3 4 5 6 |
fun main() { val values = mutableSetOf(4, 2, 3, 1, 5) val item = 3 val contains = values.contains(item) println(contains) // true } |
The default implementation of the equals() and hashCode() functions only checks for the reference equality. For instance, the following code returns false.
|
1 2 3 4 5 6 7 8 9 |
class Point public constructor(private val x: Int, private val y: Int) fun main() { val coordinates = mutableSetOf(Point(0, 0), Point(1, 2), Point(3, 4), Point(5, 6)) val origin = Point(0, 0) val contains = coordinates.contains(origin) println(contains) // false } |
Therefore, don’t forget to override equals and hashCode functions while constructing the Set of custom objects. Both these functions can be auto-generated with IntelliJ IDEA.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Point public constructor(private val x: Int, private val y: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Point if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x result = 31 * result + y return result } } fun main() { val coordinates = mutableSetOf(Point(0, 0), Point(1, 2), Point(3, 4), Point(5, 6)) val origin = Point(0, 0) val contains = coordinates.contains(origin) println(contains) // true } |
2. Using any() function
Alternately, you can use the any() function that returns true if at least one element matches with the given predicate. The following code example shows invocation for this function:
|
1 2 3 4 5 6 |
fun main() { val values = mutableSetOf(4, 2, 3, 1, 5) val item = 3 val contains = values.any { it == item } println(contains) // true } |
That’s all about determining if an element is present in a Kotlin Set.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)