Search code examples
listkotlinfindcontains

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


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?


Solution

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