Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
Víctor Martín Avatar asked Feb 27 '20 15:02

Víctor Martín


3 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
                }
            }
like image 63
A Monad is a Monoid Avatar answered Oct 27 '22 01:10

A Monad is a Monoid


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.

like image 27
forpas Avatar answered Oct 27 '22 01:10

forpas


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) }
like image 20
Suhad Bin Zubair Avatar answered Oct 27 '22 00:10

Suhad Bin Zubair