Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve insertion order in HashMap? [duplicate]

Tags:

java

hashmap

I'm using a HashMap. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this?

like image 785
realtebo Avatar asked May 22 '12 21:05

realtebo


People also ask

Does HashMap preserve order of insertion?

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.

Can we store duplicate values in HashMap?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

How do you maintain an insertion order on a map?

This class extends HashMap and 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 a LinkedHashMap, the elements will be returned in the order in which they were inserted.

What happens if the same key is inserted twice in the HashMap?

Because Map's contract is that keys must be unique. So if you associate a new value to an existing key, it will override the value of the existing entry, not create a new entry: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.


1 Answers

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

like image 77
NPE Avatar answered Sep 28 '22 08:09

NPE