I'm trying to find a value in a list of objects in kotlin, using for it "filter", but I need to return true or false if the value is found, but filter returns me a list of object in the case of match.
t.filter { it.retailerId == value }
¿How I can return a boolean when I find this value in the list of objects?
If you need that the element is exactly one:
t.filter { it.retailerId == value }.size == 1
if not:
t.any { it.retailerId == value }
With foldRight and a break when you found it:
t.foldRight(false) {val, res ->
if(it.retailerId == value) {
return@foldRight true
} else {
res
}
}
You can use firstOrNull()
with the specific predicate:
val found = t.firstOrNull { it.retailerId == value } != null
If firstOrNull()
does not return null
this means that the value is found.
For single element
list.first { it.type == 2 (eg: conditions) }
or
list.firstOrNull { it.type == 2 (eg: conditions) }
For list of elements
list.filter { it.type == 2 (eg: conditions) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With