Scala Map implementation keeping entries in insertion order?

Viewed 26537

In Java, I use LinkedHashMap for this purpose. The documentation of Java's LinkedHashMap is very clear that it has "predictable iteration order" and I need the same in Scala.

Scala has ListMap and LinkedHashMap, but the documentation on what they do exactly is poor.

Question: Is Scala's LinkedHashMap or ListMap the implementation to use for this purpose? If not, what other options are available besides using the Java's LinkedHashMap directly?

6 Answers

Scala 2.13 is introducing two new immutable implementations of Map which keep insertion order: VectorMap and SeqMap. See this PR:

Currently there isn't any known immutable map which also maintains key insertion order while keeping effectively constant lookup time on key, so the only known implementations are done by combining a Vector with a HasMap (or in Scala's case HashMap/ChampHashMap)

As of writing, Scala 2.13 is still scheduled to be released in 2018.

UPDATE 2021-04-14: Scala 3.13 does have VectorMap now. SeqMap is just a "generic trait for ordered immutable maps". Besides the new VectorMap and the older ListMap, there is also a new TreeSeqMap.

Note that mutable.ListMap got deprecated with 2.13, but immutable.ListMap is still current.

Related