Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 531
Oleksandr Karaberov Avatar asked Feb 20 '13 14:02

Oleksandr Karaberov


People also ask

Does immutable map preserve order?

util. Map. of() , it does not preserve ordering.

How do you keep an insertion order on a map?

LinkedHashMap extends HashMap. It maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is,when iterating through a collection-view of a LinkedHashMap, the elements will be returned in the order in which they were inserted.

Does HashMap maintain insertion order?

HashMap does not maintains insertion order in java. Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java. TreeMap is sorted by natural order of keys in java.

Does Scala map preserve order?

Read the part of the answer about the TreeMap using Long keys that reflect when an element was inserted. If your comparator is on the insertion order, the tree will preserve the insertion order.


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 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.

like image 171
mdm Avatar answered Sep 17 '22 02:09

mdm


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.

like image 25
dogbane Avatar answered Sep 17 '22 02:09

dogbane