如何按值对scala.collection.Map[java.lang.String, Int]进行排序?

33

如何按值(Int)对scala.collection.Map [java.lang.String,Int]进行排序? 有没有一种简洁而优雅的方法来实现这个功能?

1个回答

55

根据期望的输出集合类型(SortedMap基于键排序),您可以使用以下类似方法:

Map("foo"->3, "raise"->1, "the"->2, "bar"->4).toList sortBy {_._2}

结果将是按值排序的键值对列表:

List[(java.lang.String, Int)] = List((raise,1), (the,2), (foo,3), (bar,4))

有一种保留原始顺序的 ListMap Map 类型,如果你使用它,就能得到一个 Map:

import collection.immutable.ListMap                                          
ListMap(Map("foo"->3, "raise"->1, "the"->2, "bar"->4).toList.sortBy{_._2}:_*)

那么你就有:

scala.collection.immutable.ListMap[java.lang.String,Int] = Map((raise,1), (the,2), (foo,3), (bar,4))

(Scala 2.8)


+10,非常有用,ListMap在列表排序后保留顺序。 - virtualeyes
降序呢? - vefthym
@vefthym Map("foo"->3, "raise"->1, "the"->2, "bar"->4).toList sortWith {_._2 > _._2}(请注意,这是代码,不应翻译) - Travis Hegner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接