如何在 Scala 中将 Map[Int, Any] 转换为 SortedMap?还是树图? [英] How do I convert a Map[Int, Any] to a SortedMap in Scala? Or a TreeMap?
本文介绍了如何在 Scala 中将 Map[Int, Any] 转换为 SortedMap?还是树图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将 Map[Int, Any]
转换为 SortedMap
或 TreeMap
.有什么简单的方法吗?
I would like to convert a Map[Int, Any]
to a SortedMap
or a TreeMap
. Is there an easy way to do it?
推荐答案
假设您使用的是不可变映射
Assuming you're using immutable maps
val m = Map(1 -> "one")
val t = scala.collection.immutable.TreeMap(m.toArray:_*)
TreeMap
伴随对象的 apply 方法采用重复的映射条目参数(它们是适当参数类型的 Tuple2[_, _]
实例).toArray
生成一个 Array[Tuple2[Int, String]]
(在这种特殊情况下).: _*
告诉编译器数组的内容将被视为重复参数.
The TreeMap
companion object's apply method takes repeated map entry parameters (which are instances of Tuple2[_, _]
of the appropriate parameter types). toArray
produces an Array[Tuple2[Int, String]]
(in this particular case). The : _*
tells the compiler that the array's contents are to be treated as repeated parameters.
这篇关于如何在 Scala 中将 Map[Int, Any] 转换为 SortedMap?还是树图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文