In Java, TreeMap, HashMap, and LinkedHashMap are all implementations of the Map interface, and are all just different ways of mapping keys to values. Importantly, though, they differ in their lookup and insertion times, as well as ordering they maintain.

- HashMap is implemented as an array of linked lists, and is the implementation of a hash table most people are probably most familiar with. It offers lookup and insertion, but doesn’t maintain any ordering of its keys.
- TreeMap is implemented as a red-black tree, and so offers lookup and insertion. However, its keys are ordered according to its keys’ implementation of the interface.
- LinkedHashMap is implemented as a linked list and like HashMap offers time, but in addition maintains ordering of its keys according to the order in which they were added to the map.

When to use which? If you need to retrieve keys ordered by their implementation of (perhaps when the keys are Integers or Strings), TreeMap can do that. If you need to retrieve keys ordered by their insertion time (as in a caching system), LinkedHashMap can do that. If neither of these orderings is needed, HashMap is the best go-to, being typically faster with less overhead than the other two options.

## Recent Comments