Scala地图排序 [英] Scala map sorting

查看:74
本文介绍了Scala地图排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何对这种地图进行排序:

How do I sort a map of this kind:

"01" -> List(34,12,14,23), "11" -> List(22,11,34)

通过起始值?

推荐答案

一种方法是使用scala.collection.immutable.TreeMap,该方法始终按键排序:

One way is to use scala.collection.immutable.TreeMap, which is always sorted by keys:

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:_*)

您也可以将其转换为Seq或List并对其进行排序:

You can convert it to a Seq or List and sort it, too:

//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.

这篇关于Scala地图排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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