如何在Scala中反转LinkedHashMap元素的顺序

时间:2017-08-09 11:38:40

标签: scala collections linkedhashmap

有没有优雅的方法来反转Scala中LinkedHashMap的元素顺序?

例如,我有一个LinkedHashMap [Integer,String],如:

[1, "one"]
[2, "two"]
[3, "three"]

获取LinkedHashMap [Integer,String]的最佳方法是:

[3, "three"]
[2, "two"]
[1, "one"]

2 个答案:

答案 0 :(得分:1)

你可以做到

val reverse = for ((key, value) <- map) yield (value, key)

请注意,这不会更新旧的LinkedHashMap,但会返回一个新的。{/ p>

答案 1 :(得分:1)

import scala.collection.mutable.LinkedHashMap

val linked = LinkedHashMap(1 -> "one", 2 -> "two", 3 -> "three")

val reversed = LinkedHashMap(linked.toSeq.reverse: _*)
// reversed: scala.collection.mutable.LinkedHashMap[Int, String] = Map(3 -> three, 2 -> two, 1 -> one)