Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: how can I sort an array of tuples by their second element?

is there a way in Scala to sort an array of tuples using and arbitrary comparison function? In particular I need to sort and array of tuples by their second element, but I wanted to know a general technique to sort arrays of tuples.

Thanks!

like image 938
pau.estalella Avatar asked Apr 13 '10 08:04

pau.estalella


People also ask

How do you sort the list of tuples by the second element?

Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.

How do you sort an array with two elements?

Step 1 : Here we can take two pointers type0 (for element 0) starting from beginning (index = 0) and type1 (for element 1) starting from end index. Step 2: We intend to put 1 to the right side of the array. Once we have done this then 0 will definitely towards left side of array to achieve this we do following.


1 Answers

In scala 2.8, there is a method sortBy. Here is a simple use case:

scala> val arr = Array(("One",1),("Two",2),("Four",4),("Three",3)) arr: Array[(java.lang.String, Int)] = Array((One,1), (Two,2), (Four,4), (Three,3))  scala> arr.sortBy(_._2) res0: Array[(java.lang.String, Int)] = Array((One,1), (Two,2), (Three,3), (Four,4))  scala> 
like image 131
Eastsun Avatar answered Sep 28 '22 15:09

Eastsun