Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala merge between 2 lists base on condition

Tags:

list

scala

So i have this 2 Lists:

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 List with all the names that are equal to "Dan" with value > 0, and value is true so in my example this should return List with 1 element:

"Dan", 12.2
like image 996
david hol Avatar asked Jan 29 '26 15:01

david hol


1 Answers

Try this:

names
  .zip(list2.map(_._2))
  .filter(_._2)
  .map(_._1)
  .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:

ListBuffer(((Dan,12.2),true))

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:

ListBuffer((Dan,12.2))

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):

ListBuffer((Dan,12.2))

like image 68
Raman Avatar answered Jan 31 '26 06:01

Raman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!