What is the difference between HashMap, LinkedHashMap and TreeMap in Java?

Technology CommunityCategory: JavaWhat is the difference between HashMap, LinkedHashMap and TreeMap in Java?
VietMX Staff asked 3 years ago

All three classes implement the Map interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen:

  • HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.
  • TreeMap will iterate according to the “natural ordering” of the keys according to their compareTo()method (or an externally supplied Comparator). Additionally, it implements the SortedMap interface, which contains methods that depend on this sort order.
  • LinkedHashMap will iterate in the order in which the entries were put into the map