Question : How do you filter based on other items in a list?
I got a List that looks like that
List((2,2),(2,1),(3,1),....)
I want to keep the tupples which got the biggest second numbers when they got the same first ones
so something like that on output
List((2,2),(3,1),...)
with (2,1) removed because the 1 was < then 2 in (2,2)
so i need to filter based on other objects in the List how do you do that.
Efficiency is not really important since the list got at maximum 171 items
Converting a list of pairs to a map will use the last occurring entry when a given "key" occurs twice.
And a Tuple is sorted on the first element, then the second element, etc.
So:
List((2,2),(2,1),(3,1)).sorted.toMap
// = List((2,1),(2,2),(3,1)).toMap
// = Map((2,2), (3,1))
Just convert back to a list with .toList
afterwards, if necessary
for ((x, y) <- lst if !lst.exists(t => x == t._1 && y < t._2)) yield (x, y)
But if you want non-quadratic complexity:
lst.groupBy(_._1).map(_._2.max).toList.sorted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With