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?
util. Map. of() , it does not preserve ordering.
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.
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.
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.
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
Mapwith 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 ofImmutableMapcontains its own data and will never change.ImmutableMapis convenient forpublic static finalmaps ("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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With