December 9, 2024

HashMap, LinkedHashMap, TreeMap Examples

In this article I will show you how to create and iterate over HashMap, LinkedHashMap, TreeMap object


HashMap : HashMap is used to save key, value pair. Key should be unique including null as key. Value can be duplicate including null value. It doesn’t maintain the insertion order. I mean while iterating the hashmap object, you may not get the key value pair as per the insertion order.

package com.chetasmind.mapPackage;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.TreeMap;

public class DifferentMapExample {

	public static void main(String[] args) {
		
		System.out.println("\n ===== HashMap Example =====");
		
		HashMap<String,String>obj = new HashMap<>();
		obj.put("Suresh", "Bangalore");
		obj.put("Rajesh", "Goa");
		obj.put(null, "Delhi");
		obj.put("Neha", "Mangalore");
		
		Set<String> set = obj.keySet();
		
		for(String person: set) {
			System.out.println();
			System.out.print("Key is :"+person);
			System.out.print("  Value is :"+obj.get(person));
		}	 
	}
}

If you want to retrieve the key, value pair as per the insertion order, then you need to use LinkedHashMap. It maintains the insertion order. It allows null as key. Add below code after the for loop.

System.out.println("\n \n ======== LinkedHashMap Example ======");
		
LinkedHashMap<String,String> linkedObj = new LinkedHashMap<>();
linkedObj.put("Suresh", "Bangalore");
linkedObj.put("Rajesh", "Goa");
linkedObj.put(null, "Assam");
linkedObj.put("Neha", "Mangalore");
		
set = linkedObj.keySet();
		
for(String person: set) {
     System.out.println();
     System.out.print("Key is :"+person);
     System.out.print("  Value is :"+linkedObj.get(person));
}

While inserting the details, you want to sort the key, then go for TreeMap object. While inserting the key value pair, java internally compares the key and sorts in ascending order. TreeMap object will not accept null as key. Since null cannot be compared with other key. Add below code after the for loop.

System.out.println("\n \n ===== TreeMap Example ========");
		
TreeMap<String,String> treeMap = new TreeMap<>();
		
treeMap.put("Suresh", "Bangalore");
treeMap.put("Rajesh", "Goa");
treeMap.put("Neha", "Mangalore");
//treeMap.put(null, "Goa");  //TreeMap object will not accept null as key
		
set = treeMap.keySet();
		
for(String person: set) {
	System.out.println();
	System.out.print("Key is :"+person);
	System.out.print("  Value is :"+treeMap.get(person));
}

The above application is also present in my github repository.
If you are writing java applications for the first time, refer my Project structure article.

Leave a Reply

Your email address will not be published. Required fields are marked *