In this article, we will discuss how to sort HashMap by its Keys and Values
1. Sorting HashMap by its Keys :
- We can sort HashMap in both ascending & descending order by its keys by passing HashMap contents as argument to TreeMap class’ inter-conversion constructor
- Ascending order: use TreeMap, by passing HashMap entries as argument to inter-conversion constructor
- Descending order: use TreeMap, by implementing Comparator interface and providing reverse sorting logic and finally put all entries of HashMap to TreeMap using putAll() method of Map interface
- Check this for example to sort HashMap by its keys
2. Sorting HashMap by its Values :
- In a similar way, we can sort HashMap by its values also
- But to sort HashMap by its values, we should go through certain steps and it isn’t straightforward like sorting by keys; which uses inter-conversion constructor of TreeMap
2.1 Ascending order sorting of Values :
- get entrySet() from Map
- create List of entries using entry set
- sort using Collections class, by implementing Comparator for natural ordering of String objects
- Iterate through list of entries and store into LinkedHashMap for maintaining insertion order
- finally return HashMap or print to console by iterating using enhanced for-loop or Iterator
HashMapSortingByValuesInAsc.java
package in.bench.resources.java.map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashMapSortingByValuesInAsc {
	public static void main(String[] args) {
		// 1. create HashMap object of type <String, String>
		HashMap<String, String> companyFounder = 
				new HashMap<String, String>(); 
		// 1.1 adding key-value pairs to HashMap object
		companyFounder.put("Google", "Sundar Pichai");
		companyFounder.put("Facebook", "Mark Zuckerberg");
		companyFounder.put("Apple Inc", "Tim Cook");
		companyFounder.put("Microsoft", "Bill Gates");
		companyFounder.put("Oracle", "Larry Ellison");
		// 1.2 print to console
		System.out.println("Before Sorting for Values "
				+ "as per Insertion-Order :- \n");
		// 1.3 iterate LinkedHashMap to retrieved stored values
		for(Map.Entry<String, String> hmap : 
			companyFounder.entrySet()){
			System.out.println("Key : "  + hmap.getKey()
			+ "\t\t" + "Value : "  + hmap.getValue());
		}
		// 1.4 get entrySet from HashMap object
		Set<Map.Entry<String, String>> companyFounderSet = 
				companyFounder.entrySet();
		// 1.5 convert HashMap to List of Map entries
		List<Map.Entry<String, String>> companyFounderListEntry = 
				new ArrayList<Map.Entry<String, String>>(companyFounderSet);
		// 2. print to console
		System.out.println("\n\nSorted HashMap by its Values"
				+ " in Ascending-order :- \n");
		// 2.1 sort list of entries using Collections.sort() method
		Collections.sort(companyFounderListEntry, 
				new Comparator<Map.Entry<String, String>>() {
			@Override
			public int compare(Entry<String, String> es1, 
					Entry<String, String> es2) {
				return es1.getValue().compareTo(es2.getValue());
			}
		});
		// 2.2 store into LinkedHashMap for maintaining insertion order
		Map<String, String> companyFounderLHMap = 
				new LinkedHashMap<String, String>();
		// 2.3 iterating list and storing in LinkedHahsMap
		for(Map.Entry<String, String> map : companyFounderListEntry){
			companyFounderLHMap.put(map.getKey(), map.getValue());
		}
		// 2.4 iterate LinkedHashMap to retrieved stored values
		for(Map.Entry<String, String> lhmap : 
			companyFounderLHMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey() 
			+ "\t\t" + "Value : "  + lhmap.getValue());
		}
	}
}
Output:
Before Sorting for Values as per Insertion-Order :- 
Key : Apple Inc		Value : Tim Cook
Key : Google		Value : Sundar Pichai
Key : Microsoft		Value : Bill Gates
Key : Oracle		Value : Larry Ellison
Key : Facebook		Value : Mark Zuckerberg
Sorted HashMap by its Values in Ascending-order :- 
Key : Microsoft		Value : Bill Gates
Key : Oracle		Value : Larry Ellison
Key : Facebook		Value : Mark Zuckerberg
Key : Google		Value : Sundar Pichai
Key : Apple Inc		Value : Tim Cook
2.2 Descending order sorting of Values :
- get entrySet() from Map
- create List of entries using entry set
- sort using Collections class, by implementing Comparator for reverse sorting logic for String objects
- Iterate through list of entries and store into LinkedHashMap for maintaining insertion order
- finally return HashMap or print to console by iterating using enhanced for-loop or Iterator
HashMapSortingByValuesInDesc.java
package in.bench.resources.java.map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashMapSortingByValuesInDesc {
	public static void main(String[] args) {
		// 1. create HashMap object of type <String, String>
		HashMap<String, String> companyFounder = 
				new HashMap<String, String>(); 
		// 1.1 adding key-value pairs to HashMap object
		companyFounder.put("Google", "Sundar Pichai");
		companyFounder.put("Facebook", "Mark Zuckerberg");
		companyFounder.put("Apple Inc", "Tim Cook");
		companyFounder.put("Microsoft", "Bill Gates");
		companyFounder.put("Oracle", "Larry Ellison");
		// 1.2 print to console
		System.out.println("Before Sorting for Values "
				+ "as per Insertion-Order\n");
		// 1.3 iterate LinkedHashMap to retrieved stored values
		for(Map.Entry<String, String> hmap : 
			companyFounder.entrySet()){
			System.out.println("Key : "  + hmap.getKey()
			+ "\t\t" + "Value : "  + hmap.getValue());
		}
		// 1.4get entrySet from HashMap object
		Set<Map.Entry<String, String>> companyFounderSet = 
				companyFounder.entrySet();
		// 1.5 convert HashMap to List of Map entries
		List<Map.Entry<String, String>> companyFounderListEntry = 
				new ArrayList<Map.Entry<String, String>>(companyFounderSet);
		// 2. print to console
		System.out.println("\n\nSorted HashMap by its Values"
				+ " in Descending-Order\n");
		// 2.1 sort list of entries using Collections.sort() method
		Collections.sort(companyFounderListEntry, 
				new Comparator<Map.Entry<String, String>>() {
			@Override
			public int compare(Entry<String, String> es1, 
					Entry<String, String> es2) {
				return es2.getValue().compareTo(es1.getValue());
			}
		});
		// 2.2 store into LinkedHashMap for maintaining insertion order
		Map<String, String> companyFounderLHMap = 
				new LinkedHashMap<String, String>();
		// 2.3 iterating list and storing in LinkedHahsMap
		for(Map.Entry<String, String> map : companyFounderListEntry){
			companyFounderLHMap.put(map.getKey(), map.getValue());
		}
		// 2.4 iterate LinkedHashMap to retrieved stored values
		for(Map.Entry<String, String> lhmap : 
			companyFounderLHMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey() + "\t\t"
					+ "Value : "  + lhmap.getValue());
		}
	}
}
Output:
Before Sorting for Values as per Insertion-Order
Key : Apple Inc		Value : Tim Cook
Key : Google		Value : Sundar Pichai
Key : Microsoft		Value : Bill Gates
Key : Oracle		Value : Larry Ellison
Key : Facebook		Value : Mark Zuckerberg
Sorted HashMap by its Values in Descending-Order
Key : Apple Inc		Value : Tim Cook
Key : Google		Value : Sundar Pichai
Key : Facebook		Value : Mark Zuckerberg
Key : Oracle		Value : Larry Ellison
Key : Microsoft		Value : Bill Gates
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
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
- https://docs.oracle.com/javase/tutorial/collections/implementations/list.html
- https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
- http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
Happy Coding !!
Happy Learning !!