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?
ListMap
doesn't preserves the order of insertion.Only
LinkedHashMap
maintains the order of elements the way they are inserted.If you want to maintain order in Lists otherthan Map you can use
LinkedList
LinkedHashmap is only implemented as a mutable map ListMaps are implemented in both the mutable and immutable packages, however only the immutable ListMaps maintain the backwards ordering. (mutable listmaps do not maintain order)
The difference between the two is that
LinkedHashMap
is mutable whileListMap
is immutable. Otherwise they both areMapLike
and also preserve insertion order.Scala 2.13 is introducing two new immutable implementations of
Map
which keep insertion order:VectorMap
andSeqMap
. See this PR:"As of writing, Scala 2.13 is still scheduled to be released in 2018.
For LinkedHashMap, the answer is pretty clear that it preserves the order of insertion.
But for ListMap, it seems that there are some confuses here.
Firstly, there are two ListMap.
Secondly, the document for ListMap has something wrong as far as I tried.
mutable.ListMap
The actual order is not the insertion order as it says.
And it is not the inverse order of insertion, either. The result I tried is [forth, second, first, third]
immutable.ListMap
As the document saying that, the order is the insertion order.
One thing to notice is that it is stored internally in reversed insertion order. And the internally stored order and the iterable/traversal order are two things. The internally stored order decides the time complexity of lookup methods such as head/last/tail/init/.
From the
LinkedHashMap
Scaladoc page: