如何按其值对scala.collection.Map [java.lang.String,Int]进行排序? [英] how to sort a scala.collection.Map[java.lang.String, Int] by its values?

查看:122
本文介绍了如何按其值对scala.collection.Map [java.lang.String,Int]进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将scala.collection.Map [java.lang.String,Int]按其值排序(在Int上也是如此)?简短而优雅的方法是什么?

How would you sort a scala.collection.Map[java.lang.String, Int] by its values (so on the Int)? What is a short and elegant way to do that?

推荐答案

取决于期望的输出集合类型是什么(SortedMap在键上排序),您可以使用类似以下的东西:

Depending on what the expected output collection type is (SortedMaps are sorted on the keys), you could use something like this:

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

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

Result would be the list of key/value pairs sorted by the value:

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

有一种地图类型保留了原始顺序,ListMap.如果应用此类型,则又有一张地图:

There is a Map type that retains the original order, ListMap, if you apply this, you have a map again:

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)

(Scala 2.8)

这篇关于如何按其值对scala.collection.Map [java.lang.String,Int]进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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