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

后端 未结 7 668
悲&欢浪女
悲&欢浪女 2021-01-31 13:39

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 wante

7条回答
  •  情话喂你
    2021-01-31 14:28

    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>
    

提交回复
热议问题