Víctor Martín
Víctor Martín

Reputation: 3450

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?

Upvotes: 36

Views: 33481

Answers (6)

Louis Musole
Louis Musole

Reputation: 19

tab.none { it.property == value}

This expression return true, if the value is not found

Upvotes: 1

Suhad Bin Zubair
Suhad Bin Zubair

Reputation: 804

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

Upvotes: 3

Abhilash Das
Abhilash Das

Reputation: 1438

Kotlin has this nice extension function which u can use

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

Upvotes: 1

developer_hatch
developer_hatch

Reputation: 16224

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

Upvotes: 44

Nicola Gallazzi
Nicola Gallazzi

Reputation: 8705

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

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

Upvotes: 14

forpas
forpas

Reputation: 164089

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.

Upvotes: 9

Related Questions