Differences between hashmap and Treemap

Differences between hashmap and Treemap

Certainly! Let’s compare HashMap and TreeMap in Java, highlighting their differences in a tabular form. I’ll provide explanations and Java examples for each difference:

FeatureHashMapTreeMap
SynchronizationNot synchronized (non-thread-safe)Synchronized (thread-safe)
Null Keys and ValuesAllows null keys and multiple null valuesDoesn’t allow null keys but allows null values (throws NullPointerException)
PerformanceGenerally faster due to lack of synchronizationSlower due to synchronization overhead
OrderingNo specific order of key-value pairsSorted by keys (natural order or custom comparator)
Introduced VersionIntroduced in Java 1.2Introduced in Java 1.2
Legacy StatusNon-legacy (modern)Legacy (older)

 hashmap and Treemap

Example
Now, let’s illustrate these differences with examples: 
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;

public class HashMapVsTreeMap {
    public static void main(String[] args) {
        // Example using HashMap
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(100, "Alice");
        hashMap.put(104, "Bob");
        hashMap.put(101, "Charlie");
        hashMap.put(102, "David");

        System.out.println("-----------HashMap-----------");
        for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

        // Example using TreeMap
        TreeMap<Integer, String> treeMap = new TreeMap<>();
        treeMap.put(100, "Alice");
        treeMap.put(104, "Bob");
        treeMap.put(101, "Charlie");
        treeMap.put(102, "David");

        System.out.println("-----------TreeMap-----------");
        for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}

Output:
———–HashMap———–
100 Alice
101 Charlie
102 David
104 Bob
———–TreeMap———–
100 Alice
101 Charlie
102 David
104 Bob

Remember that HashMap provides fast access but doesn’t guarantee order, while TreeMap maintains sorted order based on keys.

Homepage

Readmore