I want to find something like ImmutableLinkedHashMap<>
in Guava library.
I need to use an immutable key-value data structure with an insertion order.
So, what should I use?

- 12,573
- 10
- 43
- 70
-
2See [Package com.google.common.collect Description](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/package-summary.html#package_description) and [ImmutableCollectionsExplained on Guava wiki](https://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained). – Grzegorz Rożniecki Feb 20 '13 at 15:01
-
Possible duplicate of [Google Collections ImmutableMap iteration order](http://stackoverflow.com/questions/3810738/google-collections-immutablemap-iteration-order) – Barett Jul 27 '16 at 17:51
2 Answers
I am not sure I am understanding exactly what you are after, but if it is a really immutable Map
, you mght want to look at ImmutableMap
As mentioned in the doc:
An immutable, hash-based
Map
with reliable user-specified iteration order. Does not permit null keys or values.Unlike
Collections.unmodifiableMap(java.util.Map<? extends K, ? extends V>)
, which is a view of a separate map which can still change, an instance ofImmutableMap
contains its own data and will never change.ImmutableMap
is convenient forpublic static final
maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller
E.g, you could use it in a similar fashion:
Map<Integer, String> m = ImmutableMap.of(5,"Five",6,"Six",7,"Seven");
Hope this is what you were after.
-
Yes I was just going to say that as well. `ImmutableMap` looks like it should work. – 808sound Feb 20 '13 at 15:00
-
The issue with this is that `ImmutableSortedMap` extends `ImmutableMap`, so if you have clients of this method, you can't enforce insertion order maintenance by types. – Max Bileschi Jan 13 '16 at 16:57
First create a LinkedHashMap
and then use ImmutableMap.copyOf(linkedHashMap)
to create an immutable copy which will have the same ordering as the original map.

- 266,786
- 75
- 396
- 414