david hol david hol - 2 months ago 5x
Scala Question

Scala merge between 2 lists base on condition

So i have this 2


val names = ListBuffer[(String, Double)]
names += ("Nat", 11.0)
names += ("Dan", 12.2)
names += ("Jeen", 0)
names += ("David", 55.0)

val list2 = ListBuffer[(String, Boolean)]
list2 += ("Nat", false)
list2 += ("Dan", true)
list2 += ("Jeen", false)
list2 += ("David", false)

So i want new
with all the names that are equal to
with value > 0, and value is
so in my example this should return
with 1 element:

"Dan", 12.2


Try this:

  .filter(_._2 > 0)

The zip combines the names list with the true/false value from the second list (I have assumed your list2 is ordered the same way as names, as shown in your example, so therefore we can drop the name in list2 with a map to just retrieve the boolean). This results in a List like:

ListBuffer(((Nat,11.0),false), ((Dan,12.2),true), ((Jeen,0.0),false), ((David,55.0),false))

Now we filter on the true/false value (_._2), resulting in a list like:


Now we don't need the boolean any more, so drop it to leave us with a list of name-value tuples via map(_._1), resulting in:


and then lastly we filter where value is > 0 with .filter(_._2 > 0), which in your example still leaves us a List with the same contents (try changing Jeen to true to see this last filter in action):