Teodorico Levoff
Teodorico Levoff

Reputation: 1659

How to sort a List of Lists of pairs of number in descending order by the second item in each pair in Scala?

I have a list that looks like this List(List(0, 2), List(0, 3), List(2, 3), List(3, 2), List(3, 0), List(2, 0))), note this list will only contain pairs and will not contain duplicate pairs. I want to sort the list in descending order by the second item in each sub list in this larger list. If there are duplicate values I don't really which comes first.

For this instance the answer could look like List(List(0,3), List(2,3), List(0,2), List(3,2), List(3,0), List(2,0))

My idea was looping through the larger list and get a list containing each second item in each pair and sort those but I am having trouble keeping track of which second item in each pair belong to which pair afterwards. Perhaps there is a more clever way?

Upvotes: 0

Views: 320

Answers (4)

evan.oman
evan.oman

Reputation: 5572

If the lists are always length 2, I would use tuples instead of lists. Then it is just a matter of using sortBy

scala> val l1 = List(List(0, 2), List(0, 3), List(2, 3), List(3, 2), List(3, 0), List(2, 0))
l1: List[List[Int]] = List(List(0, 2), List(0, 3), List(2, 3), List(3, 2), List(3, 0), List(2, 0))

scala> val l2 = l1.map(x => (x(0), x(1)))
l2: List[(Int, Int)] = List((0,2), (0,3), (2,3), (3,2), (3,0), (2,0))

scala> l2.sortBy(-_._2)
res1: List[(Int, Int)] = List((0,3), (2,3), (0,2), (3,2), (3,0), (2,0))

Upvotes: 2

Jasper-M
Jasper-M

Reputation: 15086

list.sortBy( sublist => -1 * sublist.tail.head )

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53859

You can simply do:

list.sortBy(-_(1))

Upvotes: 3

nmat
nmat

Reputation: 7591

A simple solution would be:

list.sortBy(-_.last)

Upvotes: 4

Related Questions