Check if array contains an element in Kotlin
This article explores different ways to check if an array contains an element in Kotlin.
1. Using In operator
The recommended way to check if an array contains an element is using the in operator, which provides concise and readable syntax.
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(7, 3, 4, 9, 1, 2) val target = 4 val found = target in array println(found) // true } |
The in operator is equivalent to calling the contains() function, since the expression x in y is translated to y.contains(x). The contains() function returns true if the element is found in the array.
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(7, 3, 4, 9, 1, 2) val target = 4 val found = array.contains(target) println(found) // true } |
2. Using any() function
We can check if any element of the array matches the given value using the any() function. Its usage is demonstrated below:
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(7, 3, 4, 9, 1, 2) val target = 4 val found = array.any { target == it } println(found) // true } |
We can also compare the array against multiple objects using the any() function, as follows:
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(7, 3, 4, 9, 1, 2) val values = intArrayOf(5, 9) val found = array.any(values::contains) println(found) // true } |
3. Using filter() function
Another approach is to retain all occurrences of the specified element in the array using the filter() function. Then, we can call the isNotEmpty() function to determine if that element is found or not.
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(7, 3, 4, 9, 1, 2) val target = 4 val found = array.filter { it == target }.isNotEmpty() println(found) // true } |
Alternately, we can use the count() function to get the count of the specified element in the array:
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(7, 3, 4, 9, 1, 2) val target = 4 val found = array.filter { it == target }.count() > 0 println(found) // true } |
4. Using find() function
The find() function returns the first element matching the given predicate, or null if no such element was found. We can use it as follows to determine if a value is present in the array.
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(7, 3, 4, 9, 1, 2) val target = 4 val found = array.find { it == target } != null println(found) // true } |
That’s all about checking if an array contains an element in Kotlin.
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 :)