Find if an element with a specific property value is found in a list

Viewed 12511

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?

5 Answers

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
                }
            }

In alternative to firstOrNull you can also use any with the same predicate:

val found = t.any { it.retailerId == value }

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) }

Kotlin has this nice extension function which u can use

if (none { it.isSelected == true }) {
                first().isSelected = true
            }
Related