How to Choose Between HashMap and TreeMap in Java
HashMap and TreeMap serve different purposes in Java: HashMap offers fast, unordered access using hash codes, while TreeMap maintains keys in sorted order via a red‑black tree, and the article explains their implementations, performance trade‑offs, and how to customize TreeMap ordering with comparators.
In Java, TreeMap<K,V> requires its keys to implement java.lang.Comparable, so it stores entries in a red‑black tree and iterates them in natural (ascending) order; it is suitable when ordered traversal is needed.
HashMap<K,V> uses the hashCode() of keys, distributes entries across buckets (arrays) with linked lists or trees, does not maintain order, and provides fast insertion, deletion, and lookup, making it ideal for unordered data.
Therefore, use TreeMap when a sorted result is required; otherwise, prefer HashMap for better performance in most cases.
Both classes are not thread‑safe. HashMap extends AbstractMap, which overrides equals() and hashCode() to ensure consistent hash codes for equal maps. TreeMap implements the SortedMap interface, which enforces key ordering via Comparable or a supplied Comparator.
To obtain a descending order in TreeMap, define a custom Comparator that reverses the natural comparison result and pass it to the TreeMap constructor.
static class MyComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
String param1 = (String) o1;
String param2 = (String) o2;
return -param1.compareTo(param2);
}
}Instantiate the comparator and create a TreeMap with it:
MyComparator comparator = new MyComparator();
Map
map = new TreeMap
(comparator);
Iterator iterator = map.keySet().iterator();
while(iterator.hasNext()){
String key = (String)iterator.next();
System.out.println(map.get(key));
}IT Xianyu
We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.