Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java's LinkedHashMap maintain the order of keys? [duplicate]

When LinkedHashMap.keySet() is called, will the order of the Set returned be the same as the order the keys were added in?

like image 479
Armand Avatar asked Aug 13 '10 14:08

Armand


People also ask

Does LinkedHashMap allow duplicate keys?

A LinkedHashMap cannot contain duplicate keys. LinkedHashMap can have null values and the null key. Unlike HashMap, the iteration order of the elements in a LinkedHashMap is predictable.

Is LinkedHashMap values ordered?

A LinkedHashMap is the same as a HashMap , except that the LinkedHashMap maintains the insertion order, whereas the HashMap does not.

Is LinkedHashMap sorted?

LinkedHashMap maintains insertion order. Convert LinkedHashMap into TreeMap and after that print keys of TreeMap which are sorted in nature.

Does HashMap maintain key 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.


1 Answers

Yes.

See: LinkedHashMap:

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

and from the HashMap#keySet documentation:

The set [returned] is backed by the map, so changes to the map are reflected in the set, and vice-versa.

like image 161
Tom Tresansky Avatar answered Sep 21 '22 02:09

Tom Tresansky