When to Use HashMap vs TreeMap in Java? A Practical Guide
This article explains the differences between Java's HashMap and TreeMap, covering their underlying implementations, performance characteristics, thread safety, and how to customize TreeMap for descending order, helping developers choose the right map for their needs.
Question: How to decide between HashMap and TreeMap?
Introduction
TreeMap<K,V> requires its key type to implement java.lang.Comparable, so it stores entries in natural (or provided) order using a red‑black tree. It is suitable when you need ordered traversal of keys.
HashMap<K,V> uses the key's hashCode() for distribution in buckets (array of lists or trees). It does not maintain order but offers faster insert, delete, and lookup operations.
Conclusion
If you need a sorted result, choose TreeMap; otherwise, HashMap generally provides better performance when ordering is not required.
Additional Details
1. Implementation of HashMap and TreeMap
HashMap: Based on a hash table. Keys must correctly implement hashCode() and equals() (you can override them). You can tune initial capacity and load factor to optimize space.
HashMap(): creates an empty hash map.
HashMap(Map m): creates a hash map and adds all mappings from m.
HashMap(int initialCapacity): creates an empty hash map with the specified capacity.
HashMap(int initialCapacity, float loadFactor): creates an empty hash map with the specified capacity and load factor.
TreeMap: Based on a red‑black tree. It has no tuning options because the tree stays balanced.
TreeMap(): creates an empty map.
TreeMap(Map m): creates a map and adds all entries from m.
TreeMap(Comparator c): creates a map that orders keys using the given comparator.
TreeMap(SortedMap s): creates a map with entries from s, using the same comparator as s.
2. Thread safety
Both HashMap and TreeMap are not thread‑safe. HashMap extends AbstractMap, while TreeMap implements SortedMap.
AbstractMap: Provides implementations of equals() and hashCode() so that two maps with the same entries are considered equal regardless of internal order.
SortedMap: Defines a view of the map with ordered keys. Implementations must ensure keys are comparable or a Comparator is supplied; TreeMap is the sole implementation.
3. Making TreeMap sort in descending order
Provide a custom Comparator that reverses the natural order.
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);
}
}Use the comparator when constructing the TreeMap:
MyComparator comparator = new MyComparator();
Map<String,String> map = new TreeMap<String,String>(comparator);Full example that inserts entries and iterates in descending order:
public class MapTest {
public static void main(String[] args) {
MyComparator comparator = new MyComparator();
Map<String,String> map = new TreeMap<String,String>(comparator);
map.put("a","a");
map.put("b","b");
map.put("f","f");
map.put("d","d");
map.put("c","c");
map.put("g","g");
Iterator iterator = map.keySet().iterator();
while(iterator.hasNext()){
String key = (String)iterator.next();
System.out.println(map.get(key));
}
}
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);
}
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
