Home » Java » Core Java » Java TreeMap Vs HashMap With Examples

About Venkatesh Nukala

Venkatesh Nukala
Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com

Java TreeMap Vs HashMap With Examples

A quick guide to understand the differences between the TreeMap and HashMap with examples.

1. Overview

In this tutorial, We will learn the core differences between TreeMap and HashMap classes with example programs.

If you are new to java programming, suggest to go through the below topics.

HashMap Examples

TreeMap Examples

In java, All Map implementations are to store the key-value pairs but there are few differences based on the implementations.

HashMap is extensively used in the day to day development from the collection framework when compared to TreeMap. Both uses internally bucketing concept but when any bucket partition becomes large the it does convert into TreeNode Structure.

2. Similarities between HashMap and TreeMap

The below are the common things in both classes. Let us look into those before understanding the differences.

2.1 HashMap and TreeMap classes implement Map<K,V>, Cloneable, Serializable interfaces and extends AbstractMap<K,V> class.

2.2 Both stores the values based on the keys. Always key and value should be provided.

2.3 Always key should be unique and if we add the same key again then old value will be replaced with the new value.

2.4 These are not synchronized.

2.5 Not thread-safe because if the original Map is modified during the iteration then it cause to throw runtime exception ConcurrentModificationException.

3. HashMap Examples

In the below example, we added few values to HashMap using put() method. Next, printed the all the values of HashMap.

Further tried to print the values using iterator and deleted the key “0333” from the original hashmap.

Removal key from hashmap produces the runtime exception.

package com.javaprogramto.collections.hashmap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExamples {

	public static void main(String[] args) {

		Map<String, String> hashMap = new HashMap<>();

		hashMap.put("0111", "one's");
		hashMap.put("0222", "two's");
		hashMap.put("0333", "three's");
		hashMap.put("0444", "four's");
		hashMap.put("0111", "one's modified");

		System.out.println("HashMap values are - " + hashMap);

		System.out.println("Iterating Hashmap and modifying the values");

		Set<String> keys = hashMap.keySet();

		Iterator<String> iterator = keys.iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println("key - " + key + ", value - " + hashMap.get(key));
			if (key == "0333") {
				hashMap.remove(key);
			}
		}

	}

}

Output:

HashMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating Hashmap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1490)
	at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1513)
	at com.javaprogramto.collections.hashmap.HashMapExamples.main(HashMapExamples.java:29)

4. TreeMap Examples

In the below example, we added few values to TreeMap using put() method. Next, printed the all the values of TreeMap in sorted order.

Further tried to print the values using iterator and deleted the key “0333” from the original treemap.

Removal key from treemap produces the runtime exception.

package com.javaprogramto.collections.treemap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapExamples {

	public static void main(String[] args) {

		Map<String, String> treeMap = new TreeMap<>();

		treeMap.put("0111", "one's");
		treeMap.put("0222", "two's");
		treeMap.put("0333", "three's");
		treeMap.put("0444", "four's");
		treeMap.put("0111", "one's modified");

		System.out.println("treeMap values are - " + treeMap);

		System.out.println("Iterating treeMap and modifying the values");

		Set<String> keys = treeMap.keySet();

		Iterator<String> iterator = keys.iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println("key - " + key + ", value - " + treeMap.get(key));
			if (key == "0333") {
				treeMap.remove(key);
			}
		}

	}
}

Output:

treeMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating treeMap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208)
	at java.base/java.util.TreeMap$KeyIterator.next(TreeMap.java:1262)
	at com.javaprogramto.collections.treemap.TreeMapExamples.main(TreeMapExamples.java:29)

5. Differences between HashMap and TreeMap

The below are the main differences between these two maps.

5.1 TreeMap implements the NavigableMap interfaces rather than Map interface.

5.2 HashMap is implemented based on the hashtable

     TreeMap is implemented based on Tree Structured based map such as Red Black Tree which is a balanced.

5.3 HashMap allows only one null key and multiple null values.

      TreeMap does not allow null key but allows null values.

5.4 HashMap does not sort the keys where as TreeMap does sort the keys.

5.5 HashMap is faster then TreeMap because hashmap does not sort so it provides easy access to insertion and retrieval with constant time O(1) with put() and get() methods.

5.6 HashMap uses the equals() method for duplicate keys comparison but for TreeMap, keys are compared and sorted based on the compareTo() method. So, key must implement the Comparator or Comparable interface else will get the runtime error.

6. Conclusion

In this article, We’ve seen the first example programs on HashMap and TreeMap classes and next similarities and differences between HashMap and TreeMap.

GitHub HashMap

GitHub TreeMap

Java 8 Stream map() and filter() methods

Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Java TreeMap Vs HashMap With Examples

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments