How can I 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 another way?
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.
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
}
array.indexIf(Object o) -> will return you index of first founded element, array.lastIndexOf(Object o) -> will return you index of last founded element. You can also use predicate too, etc array.indexOfLast { it.name == "test " } or array.indexOfFirst { it.name == "test "}