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

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

    On Scala 2.8 (yes, again :), you can also do this:

    val v = Array(('a', 2), ('b', 1))
    scala.util.Sorting.stableSort(v)(manifest[(Char, Int)], Ordering.by(_._2))
    

    In the specific case of pairs, this can also work to sort first by the second element, and then by the first:

    scala.util.Sorting.stableSort(v)(manifest[(Char, Int)], Ordering.by(_.swap))
    

提交回复
热议问题