I need an immutable key-value structure that retains insertion order

Oleksandr Karaberov picture Oleksandr Karaberov · Feb 20, 2013 · Viewed 11.7k times · Source

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?

Answer

mdm picture mdm · Feb 20, 2013

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 of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public 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.