Check if an array contains a specific value in Kotlin
This article explores different ways to check whether an array contains the specified value or not in Kotlin.
1. Using contains() function
The utility function to check the presence of an element in an array is with the contains() function.
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> isPresent(arr: Array<T>, target: T): Boolean { return arr.contains(target) } fun main() { var arr = arrayOf(4, 7, 3, 5, 2) val key = 5 println(isPresent(arr, key)) // true } |
2. Using ‘In’ operator
Kotlin provides an In operator, which is an alternative syntax for contains.
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> isPresent(arr: Array<T>, target: T): Boolean { return target in arr } fun main() { var arr = arrayOf(4, 7, 3, 5, 2) val key = 5 println(isPresent(arr, key)) // true } |
3. Using indexOf() function
Alternatively, you can use the indexOf() function as follows:
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> isPresent(arr: Array<T>, target: T): Boolean { return arr.indexOf(target) >= 0 } fun main() { var arr = arrayOf(4, 7, 3, 5, 2) val key = 5 println(isPresent(arr, key)) // true } |
4. Using any() function
Another plausible way is to use the any() function, which returns true if at least one element in the array matches the given predicate.
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> isPresent(arr: Array<T>, target: T): Boolean { return arr.any{ i -> i == target } } fun main() { var arr = arrayOf(4, 7, 3, 5, 2) val key = 5 println(isPresent(arr, key)) // true } |
5. Using filter() function
You can also use the filter() function to check if an array contains a specified value, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> isPresent(arr: Array<T>, target: T): Boolean { return arr.filter { x: T -> x == target } .count() > 0 } fun main() { var arr = arrayOf(4, 7, 3, 5, 2) val key = 5 println(isPresent(arr, key)) // true } |
6. Linear search
You can also perform a linear search on the given array to check for the specified value in the array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun <T> isPresent(arr: Array<T>, target: T): Boolean { for (s in arr) { if (target == s) { return true } } return false } fun main() { var arr = arrayOf(4, 7, 3, 5, 2) val key = 5 println(isPresent(arr, key)) // true } |
That’s all about determining whether an array contains a specific value 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 :)