$show=/label

Java TreeMap Vs HashMap With Examples

SHARE:

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.

Java TreeMap Vs HashMap With Examples


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

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,17,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,29,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,93,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,35,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,14,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,111,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,105,Java Spark,1,java.lang,5,java.util. function,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,1,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,28,String,59,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java TreeMap Vs HashMap With Examples
Java TreeMap Vs HashMap With Examples
A quick guide to understand the differences between the TreeMap and HashMap with examples.
https://1.bp.blogspot.com/-g6S_BGix6P4/YBA2lohsSgI/AAAAAAAADOc/Mi0IzkitJVkkRxfpWbruw7EuzRdkzs99ACLcBGAsYHQ/w400-h296/Java%2BTreeMap%2BVs%2BHashMap%2BWith%2BExamples.png
https://1.bp.blogspot.com/-g6S_BGix6P4/YBA2lohsSgI/AAAAAAAADOc/Mi0IzkitJVkkRxfpWbruw7EuzRdkzs99ACLcBGAsYHQ/s72-w400-c-h296/Java%2BTreeMap%2BVs%2BHashMap%2BWith%2BExamples.png
JavaProgramTo.com
https://www.javaprogramto.com/2021/01/java-treemap-vs-hashmap..html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/01/java-treemap-vs-hashmap..html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content