Kotlin - Idiomatic way to check array contains value
ArraysKotlinArrays Problem Overview
What's an idiomatic way to check if an array of strings contains a value in Kotlin? Just like ruby's #include?
.
I thought about:
array.filter { it == "value" }.any()
Is there a better way?
Arrays Solutions
Solution 1 - Arrays
The equivalent you are looking for is the contains operator.
array.contains("value")
Kotlin offer an alternative infix notation for this operator:
"value" in array
It's the same function called behind the scene, but since infix notation isn't found in Java we could say that in
is the most idiomatic way.
Solution 2 - Arrays
You could also check if the array contains an object with some specific field to compare with using any()
listOfObjects.any{ object -> object.fieldxyz == value_to_compare_here }
Solution 3 - Arrays
Here is code where you can find specific field in ArrayList with objects. The answer of Amar Jain helped me:
listOfObjects.any{ it.field == "value"}
Solution 4 - Arrays
Using in operator is an idiomatic way to do that.
val contains = "a" in arrayOf("a", "b", "c")
Solution 5 - Arrays
You can use the in
operator which, in this case, calls contains
:
"value" in array
Solution 6 - Arrays
You can use it..contains(" ")
data class Animal (val name:String)
val animals = listOf(Animal("Lion"), Animal("Elephant"), Animal("Tiger"))
println(animals.filter { it.name.contains("n") }.toString())
output will be
[Animal(name=Lion), Animal(name=Elephant)]
Solution 7 - Arrays
You can use find
method, that returns the first element matching the given [predicate], or null
if no such element was found.
Try this code to find value
in array
of objects
val findedElement = array?.find {
it.id == value.id
}
if (findedElement != null) {
//your code here
}