Java – Converting Unordered HashMap into Sorted TreeMap

In this article, we will discuss how to convert unordered HashMap into Sorted TreeMap

We can sort HashMap in both ascending and descending order, by passing HashMap contents as argument to TreeMap’s inter-conversion constructor

1. Solution for HashMap to TreeMap for Keys :

  1. Ascending order: pass HashMap entries as arguments to TreeMap class’ inter-conversion constructor
  2. Descending order: Implement Comparator interface by providing reverse sorting logic and finally putting all entries of HashMap into TreeMap classs using putAll() method

1.1 Sorting in Ascending order of Keys :

  • Converting Unordered HashMap to Sorted TreeMap in ascending order
  • Syntax :
TreeMap<String, String> set = new TreeMap<String, String>(hashMap);

SortingHashMapInAscendingOrder.java

package in.bench.resources.java.map;

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

public class SortingHashMapInAscendingOrder {

	public static void main(String[] args) {

		// 1. create HashMap object of type <String, String>
		HashMap<String, String> hm = new HashMap<String, String>(); 


		// 1.1 adding key-value pairs to HashMap object
		hm.put("Microsoft", "Bill Gates");
		hm.put("Apple Inc", "Steve Jobs");
		hm.put("Google", "Sundar Pichai");
		hm.put("LinkedIn", "Reid Hoffman");
		hm.put("Facebook", "Mark Zuckerberg");


		// 1.2 print to console - Random Order iterating
		System.out.println("Before Sorting : Random Order \n");


		// 1.3 getting keySet() into Set
		Set<String> set = hm.keySet();


		// 1.4 get Iterator from key set
		Iterator<String> itr = set.iterator();


		// 1.5 iterating in random order
		while(itr.hasNext()) {
			String key = itr.next();
			System.out.println("Key : "  + key + "\t\t"
					+ "Value : "  + hm.get(key));
		}


		// 2. After Sorting : Ascending order
		System.out.println("\n\n\nAfter Sorting : Ascending order of Keys \n");


		// 2.1 convert to TreeMap
		Map<String, String> ts = new TreeMap<String, String>(hm);


		// 2.2 iterate/print - ascending order of keys
		for(String strKey : ts.keySet()){
			System.out.println("Key : "  + strKey + "\t\t"
					+ "Value : "  + hm.get(strKey));
		}
	}
}

Output:

Before Sorting : Random Order 

Key : Apple Inc		Value : Steve Jobs
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Microsoft		Value : Bill Gates
Key : Facebook		Value : Mark Zuckerberg



After Sorting : Ascending order of Keys 

Key : Apple Inc		Value : Steve Jobs
Key : Facebook		Value : Mark Zuckerberg
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Microsoft		Value : Bill Gates

1.2 Sorting in Descending order of Keys :

  • Converting Unordered HashMap to Sorted TreeMap in descending order
  • Syntax :
TreeMap<String, String> map = new TreeMap<String, String>(reverseCompLogic);
 
map.putAll(hashMap);

SortingHashMapInDescendingOrder.java

package in.bench.resources.java.map;

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

public class SortingHashMapInDescendingOrder {

	public static void main(String[] args) {

		// 1. create HashMap object of type <String, String>
		HashMap<String, String> hm = new HashMap<String, String>(); 


		// 1.1 adding key-value pairs to HashMap object
		hm.put("Microsoft", "Bill Gates");
		hm.put("Apple Inc", "Steve Jobs");
		hm.put("Google", "Sundar Pichai");
		hm.put("LinkedIn", "Reid Hoffman");
		hm.put("Facebook", "Mark Zuckerberg");

		// 1.2 print to console - Random Order iterating
		System.out.println("Before Sorting : Random Order \n");


		// 1.3 getting keySet() into Set
		Set<String> set = hm.keySet();

		// get Iterator from key set
		Iterator<String> itr = set.iterator();


		// 1.4 iterating in random order
		while(itr.hasNext()) {
			String key = itr.next();
			System.out.println("Key : "  + key + "\t\t"
					+ "Value : "  + hm.get(key));
		}

		// 2. After Sorting : Ascending order
		System.out.println("\n\n\nAfter Sorting : Descending order of Keys \n");


		// 2.1 convert to TreeMap
		Map<String, String> ts = new TreeMap<String, String>(
				Collections.reverseOrder());


		// 2.2 put all key-value into TreeMap
		ts.putAll(hm);


		// 2.3 iterate/print - descending order of keys
		for(String strKey : ts.keySet()){
			System.out.println("Key : "  + strKey + "\t\t"
					+ "Value : "  + hm.get(strKey));
		}
	}
}

Output:

Before Sorting : Random Order 

Key : Apple Inc		Value : Steve Jobs
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Microsoft		Value : Bill Gates
Key : Facebook		Value : Mark Zuckerberg



After Sorting : Descending order of Keys 

Key : Microsoft		Value : Bill Gates
Key : LinkedIn		Value : Reid Hoffman
Key : Google		Value : Sundar Pichai
Key : Facebook		Value : Mark Zuckerberg
Key : Apple Inc		Value : Steve Jobs

2. String & Wrapper classes v/s Custom Object :

3. Important points to remember about Map :

  • HashMap stores entries (Key-Value pairs) in random-order of Keys
  • LinkedHashMap stores entries (Key-Value pairs) as per insertion-order of Keys
  • TreeMap stores entries (Key-Value pairs) in sorted-order of Keys

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Sorting HashMap by Keys and Values
Java - How to iterate through LinkedHashMap in reverse-order ?