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!
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.
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.
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>
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