ClassNotFoundException
ClassNotFoundException

Reputation: 409

How To Reverse The Order Of LinkedHashMap Elements In Scala

Is there any elegant way to reverse the elements' order of LinkedHashMap in Scala?

For instance, I have a LinkedHashMap[Integer, String] like:

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

What is the best way to get a LinkedHashMap[Integer, String] like:

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

Upvotes: 0

Views: 433

Answers (2)

Jeffrey Chung
Jeffrey Chung

Reputation: 19527

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)

Upvotes: 1

Bruno
Bruno

Reputation: 250

You can do

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

Note that this will not update the old LinkedHashMap, but will return a new one.

Upvotes: 0

Related Questions