scala 对对象列表进行排序的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9751434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simplest way to sort list of objects
提问by Chris
I have a list of objects of type A. In a first iteration I assign each object a double value 0 < x < 1 and then want to sort each object according to it's x value.
我有一个类型为 A 的对象列表。在第一次迭代中,我为每个对象分配了一个双精度值 0 < x < 1,然后想根据它的 x 值对每个对象进行排序。
Currently I use a wrapper class that stores the object and it's x value to make a comparable list.
目前我使用一个包装类来存储对象和它的 x 值来制作一个可比较的列表。
Is there a datatype provided by Scala that allows me something like:
是否有 Scala 提供的数据类型允许我执行以下操作:
var result = new SortedList[Double, A]
result.insert(x,a)
result.insert(x1,a1)
result.insert(x2,a2)
and then
接着
println(result.mkString)
回答by Destin
You can actually do this quite easily with normal Scala lists and their sortBymethod. Here's a brief REPL session showing how:
实际上,使用普通的 Scala 列表及其sortBy方法可以很容易地做到这一点。这是一个简短的 REPL 会话,展示了如何:
scala> class A(val value: Double) { override def toString = "A:" + value }
defined class A
scala> List(new A(6), new A(1), new A(3)) sortBy (_.value)
res0: List[A] = List(A:1.0, A:3.0, A:6.0)
回答by Luigi Plinge
Use tuples instead of creating a new wrapper class.
使用元组而不是创建新的包装类。
List((1.2, "a1"), (0.1, "a2"), (0.9, "a3")).sorted
// List((0.1,a2), (0.9,a3), (1.2,a1))
回答by JasonG
I go like this. For getting top c words in a hashmap:
我就这样去。要在哈希图中获取前 c 个单词:
def getTopCWordsDeclarative(input: mutable.HashMap[String, Int], c: Int): Map[String, Int] = {
val sortedInput = input.toList.sortWith(_._2 > _._2)
sortedInput.take(c).toMap
}

