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

后端 未结 7 653
悲&欢浪女
悲&欢浪女 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:41

    You can use this code:

    scala> val v = Array(('a', 2), ('b', 1))
    v: Array[(Char, Int)] = Array((a,2), (b,1))
    
    scala> scala.util.Sorting.stableSort(v,
         | (e1: (Char, Int), e2: (Char, Int)) => e1._2 < e2._2)
    
    scala> v
    res11: Array[(Char, Int)] = Array((b,1), (a,2))
    

    Unfortunetly, it seems that Scala cannot infer the type of the array passed to stableSort. I hope that's ok for you.

    0 讨论(0)
提交回复
热议问题