In this quick post, we’re gonna look at the similarities as well as the differences between Java HashMap and TreeMap.
Before we dive into the differences between Java HashMap and TreeMap, let’s first look at their similarities:
Collections.synchronizedMap(map)
where the map is the name of our Map.
Map<Integer, String> hashMap = new HashMap<>(); hashMap.put(1, "Selena"); hashMap.put(1, "Harry"); System.out.println(hashMap.size()); //prints 1 System.out.println(hashMap.get(1)); //prints Harry Map<Integer, String> treeMap = new TreeMap<>(); treeMap.put(1, "Selena"); treeMap.put(1, "Harry"); System.out.println(treeMap.size()); //prints 1 System.out.println(treeMap.get(1)); //prints Harry
Rather any Java Map implementation doesn’t allow duplicate keys
Map<Integer, String> hashMap = new HashMap<>(); hashMap.put(1, "Selena"); hashMap.put(2, "Harry"); for(Map.Entry<Integer, String> entry : hashMap.entrySet()) { hashMap.remove(2); //throws ConcurrentModificationException }
Now that we’re aware of how similar they are, let’s look at the differences:
Map<Integer, String> treeMap = new TreeMap<>(); treeMap.put(5, "Harry"); treeMap.put(1, "Jack"); treeMap.put(2, "Selena"); System.out.println(treeMap.keySet()); // prints [1, 2, 5]
HashMap doesn’t guarantee any specific ordering of elements. We can’t predict the order in which the elements will be stored in it.
Map<Integer, String> treeMap = new TreeMap<>(); treeMap.put(null, "Harry"); //throws NullPointerException Map<Integer, String> hashMap = new HashMap<>(); hashMap.put(null, null); //works fine
This is because the default compare() or compareTo() method implementations throw a NullPointerException. However, when using a TreeMap with a custom Comparator, the compare() method implementation determines how the null key and values are handled
Whether to opt for a HashMap or a TreeMap will depend upon the application requirements. Let’s look at the general guideline to help us decide which data structure to use:
In this quick tutorial, we looked at the similarities and differences between two extremely popular Java Map implementations – HashMap and TreeMap.
There’s an article: Java Code Geeks-TreeMap that I recommend checking out to learn more about Java TreeMap.