Java 21+
SequencedMap
Difference between HashMap, LinkedHashMap and TreeMap
The first is unordered, while the other two are sequenced.
As of Java 21, we have the SequencedMap interface. With this interface, we can add/retrieve directly the first/last entries. And we can easily traverse the collection in reverse if need be.
For more info, study JEP 431: Sequenced Collections. And watch the excellent presentation by Stuart Marks, technical lead of this feature.
Of the three classes you mention, two implement this interface.
The LinkedHashMap class keeps its entries in insertion-order, or, optionally, access-order.
The TreeMap class its entries in the natural order of its keys. Or, alternatively, you can specify a Comparator to be used in sorting the keys.
Both LinkedHashMap & TreeMap iterate through entries in a predictable reliable encounter-order.
SequencedMap is now the super-interface of ConcurrentNavigableMap, NavigableMap, and SortedMap.
In contrast, HashMap implements Map but not SequencedMap (nor ConcurrentNavigableMap, NavigableMap, SortedMap). So entries in a HashMap have no predictable encounter-order. Indeed, the order may even change between iterations.
| Class |
Map |
SequencedMap |
ConcurrentNavigableMap |
NavigableMap |
SortedMap |
LinkedHashMap |
✅ |
✅ |
❌ |
❌ |
❌ |
TreeMap |
✅ |
✅ |
❌ |
✅ |
✅ |
ConcurrentSkipListMap |
✅ |
✅ |
✅ |
✅ |
✅ |
HashMap |
✅ |
❌ |
❌ |
❌ |
❌ |
Decision tree
If you want a Map with fast access to any arbitrary entry by key:
- Use
HashMap.
- If accessed across threads, use
ConcurrentHashMap.
- If you want an entry removed automatically when no other references to its key remain, use
WeakHashMap.
If you want the keys maintained in a certain order, use a SequencedMap:
- If you want the keys kept in insertion-order (or access-order), choose
LinkedHashMap as your implementation of SequencedMap.
- If you want the keys to sort themselves, “natural order”, choose
TreeMap.
- If you want to provide a
Comparator to sort those keys,
also choose TreeMap.
- If you have a large number of elements, or need access across threads, choose
ConcurrentSkipListMap instead of TreeMap.
You can retrieve a SequencedSet of the keys from a SequencedMap by calling sequencedKeySet.
If your keys are of an enum type, and you want the keys kept in the order in which the enum declares, use EnumMap. For example, Map < java.time.Month , Employee > monthlyAssignmentMap = new EnumMap<>() ;.
In the rare cases wherein reference-equality semantics are required, use IdentityHashMap.
Avoid the legacy class Hashtable.