Issue
I have a list of elements, for example:
val myList = listOf(1,2,3,4,5,6,7)
The list could be of any type, this is just an example. Now I have a list of predicates of arbitrary length:
val myPredicates = listOf({myInt: Int -> myInt > 1}, {myInt: Int -> myInt%2 == 0})
How do I filter the list by applying all the predicates, in order of the list, to myList
and get the result in a new list? I feel like the answer lies somewhere in using the reduce
or fold
operator, but the answer is eluding me.
Solution
The simplest solution I can think of is using all on the predicates list in your filter
call like this:
myList.filter { elt -> myPredicates.all { it(elt) } }
The part myPredicates.all { it(elt) }
returns true when all predicates are true for the given element elt
.
Answered By - Joffrey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.