斯卡拉:我怎么能由他们的第二个元素进行排序元组的数组? [英] Scala: how can I sort an array of tuples by their second element?

查看:127
本文介绍了斯卡拉:我怎么能由他们的第二个元素进行排序元组的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在斯卡拉的方式使用排序元组数组和任意比较函数?特别是我需要通过他们的第二个元素进行排序和元组的数组,但我想知道一般的技术,元组数组进行排序。

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.

谢谢!

推荐答案

您可以使用此code:

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))

偏偏,似乎斯卡拉不能推断传递到 stableSort 数组的类型。我希望这是确定适合你。

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

这篇关于斯卡拉:我怎么能由他们的第二个元素进行排序元组的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆