user1744056
user1744056

Reputation:

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

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?

Upvotes: 24

Views: 15230

Answers (2)

mdm
mdm

Reputation: 3988

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.

Upvotes: 34

dogbane
dogbane

Reputation: 274632

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.

Upvotes: 10

Related Questions