scala Scala地图排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4793490/
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
Scala map sorting
提问by Adrian Modliszewski
How do I sort a map of this kind:
我如何对这种地图进行排序:
"01" -> List(34,12,14,23), "11" -> List(22,11,34)
by the beginning values?
按初始值?
回答by Landei
One way is to use scala.collection.immutable.TreeMap, which is always sorted by keys:
一种方法是使用 scala.collection.immutable.TreeMap,它总是按键排序:
val t = TreeMap("01" -> List(34,12,14,23), "11" -> List(22,11,34))
//If you have already a map...
val m = Map("01" -> List(34,12,14,23), "11" -> List(22,11,34))
//... use this
val t = TreeMap(m.toSeq:_*)
You can convert it to a Seq or List and sort it, too:
您也可以将其转换为 Seq 或 List 并对其进行排序:
//by specifying an element for sorting
m.toSeq.sortBy(_._1) //sort by comparing keys
m.toSeq.sortBy(_._2) //sort by comparing values
//by providing a sort function
m.toSeq.sortWith(_._1 < _._1) //sort by comparing keys
There are plenty of possibilities, each more or less convenient in a certain context.
有很多可能性,每种可能性在特定情况下或多或少都方便。
回答by Kevin Wright
As stated, the default Maptype is unsorted, but there's always SortedMap
如前所述,默认Map类型是未排序的,但总是有SortedMap
import collection.immutable.SortedMap
SortedMap("01" -> List(34,12,14,23), "11" -> List(22,11,34))
Although I'm guessing you can't use that, because I recognise this homework and suspect that YOUR map is the result of a groupBy operation. So you have to create an empty SortedMap and add the values:
虽然我猜你不能使用它,因为我认出了这个作业并怀疑你的地图是 groupBy 操作的结果。所以你必须创建一个空的 SortedMap 并添加值:
val unsorted = Map("01" -> List(34,12,14,23), "11" -> List(22,11,34))
val sorted = SortedMap.empty[String, List[Int]] ++ unsorted
//or
val sorted = SortedMap(unsorted.toSeq:_*)
Or if you're not wedded to the Mapinterface, you can just convert it to a sequence of tuples. Note that this approach will only work if both the keys and values have a defined ordering. Lists don't have a default ordering defined, so this won't work with your example code - I therefore made up some other numbers instead.
或者,如果您不喜欢Map接口,则可以将其转换为一系列元组。请注意,此方法仅在键和值都具有定义的顺序时才有效。列表没有定义默认排序,因此这不适用于您的示例代码 - 因此我编造了一些其他数字。
val unsorted = Map("01" -> 56, "11" -> 34)
val sorted = unsorted.toSeq.sorted
This might be useful if you can first convert your lists to some other type (such as a String), which is best done using mapValues
如果您可以先将列表转换为其他类型(例如字符串),这可能很有用,最好使用 mapValues
update:See Landei's answer, which shows how you can provide a custom sort function that'll make this approach work.
更新:请参阅 Landei 的回答,其中显示了如何提供使这种方法起作用的自定义排序功能。

