Reputation: 17617
I have two lists:
val l1 = List(1, 2, 3, 4)
val l2 = List(true, false, true, true)
Is there a nice and short way to filter l1
based on l2
?
ris = List(1, 3, 4)
Upvotes: 1
Views: 3397
Reputation: 20405
Using a for comprehension which desugars into flatMap
and withFilter
(lazy filtering), like this,
for ( (a,b) <- l1.zip(l2) if b ) yield a
Upvotes: 0
Reputation: 8103
One way could be zipping and then filtering l1.zip(l2).filter(_._2).map(_._1)
:
scala> l1.zip(l2)
res0: List[(Int, Boolean)] = List((1,true), (2,false), (3,true), (4,true))
scala> .filter(_._2)
res1: List[(Int, Boolean)] = List((1,true), (3,true), (4,true))
scala> .map(_._1)
res2: List[Int] = List(1, 3, 4)
Upvotes: 2