Donbeo
Donbeo

Reputation: 17617

scala filter a list based on the values of another list

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

Answers (3)

elm
elm

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

Dima
Dima

Reputation: 40500

A little shorter:

list1.zip(list2).collect { case (x, true) => x }

Upvotes: 8

Filippo Vitale
Filippo Vitale

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

Related Questions