Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala filtering tuple list

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

like image 422
pastjean Avatar asked Nov 27 '22 18:11

pastjean


2 Answers

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

like image 151
Kevin Wright Avatar answered Dec 04 '22 03:12

Kevin Wright


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
like image 44
axel22 Avatar answered Dec 04 '22 02:12

axel22