Scala filter tuple list

Question. How do you filter based on other items in a list?

I got a list that looks like

List((2,2),(2,1),(3,1),....) 

I want to keep the ones that got the biggest numbers when they got the same first

so something like this in output

 List((2,2),(3,1),...) 

with (2,1) removed since 1 was <then 2 in (2,2)

so i need to filter based on other objects in the list how you do it.

Efficiency is not very important as the list received a maximum of 171 items

+4
source share
2 answers
 for ((x, y) <- lst if !lst.exists(t => x == t._1 && y < t._2)) yield (x, y) 

But if you want non-squared complexity:

 lst.groupBy(_._1).map(_._2.max).toList.sorted 
+11
source

When converting a list of pairs to a card, the last occurrence will be used when this “key” occurs twice.

And the tuple is sorted by the first element, then by 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 go back to the list with .toList after that if necessary

+16
source

Source: https://habr.com/ru/post/1332696/


All Articles