Sorting HashMap by Keys and Values

In this article, we will discuss how to sort HashMap by its Keys and Values

1. Sorting HashMap by Keys:

  • We can sort HashMap in both ascending and descending order by its keys
  • by passing HashMap contents as argument to TreeMap class’ inter-conversion constructor

Solution:

  • Ascending order: use TreeMap, by passing HashMap entries as arguments to inter-conversion constructor
  • Descending order: use TreeMap, by implementing Comparator interface and providing reverse sorting logic and finally putting all entries of HashMap to TreeMap using putAll() method of Map interface
  • Click here for example to sort HashMap by its keys

2. Sorting HashMap by 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 that straightforward like sorting by keys; which uses inter-conversion constructor of TreeMap

2.1 Ascending order sorting:

  1. get entrySet() from Map
  2. create List of entries using entry set
  3. sort using Collections class, by implementing Comparator for natural ordering of String objects
  4. Iterate through list of entries and store into LinkedHashMap for maintaining insertion order
  5. finally return HashMap or print to console by iterating using enhanced for-loop or Iterator
  6. Read Example 1 – Sorting in ascending order by its values

2.2 Descending order sorting:

  1. get entrySet() from Map
  2. create List of entries using entry set
  3. sort using Collections class, by implementing Comparator for reverse sorting logic for String objects
  4. Iterate through list of entries and store into LinkedHashMap for maintaining insertion order
  5. finally return HashMap or print to console by iterating using enhanced for-loop or Iterator
  6. Read Example 2 – Sorting in descending order by its values

 

Example 1: Sorting in ascending order of values:

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) {

		// creating HashMap object of type <String, String>
		HashMap<String, String> companyFounder = 
				new HashMap<String, String>(); 

		// adding key-value pairs to HashMap object
		companyFounder.put("Google", "Sundar Pichai");
		companyFounder.put("Facebook", "Mark Zuckerberg");
		companyFounder.put("LinkedIn", "Reid Hoffman");
		companyFounder.put("Apple", "Tim Cook");
		companyFounder.put("Microsoft", "Bill Gates");
		companyFounder.put("Amazon", "Jeff Bezos");
		companyFounder.put("Oracle", "Larry Ellison");

		System.out.println("Before Sorting for Values "
				+ "as per Insertion-Order\n");

		// 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());
		}

		// get entrySet from HashMap object
		Set<Map.Entry<String, String>> companyFounderSet = 
				companyFounder.entrySet();

		// convert HashMap to List of Map entries
		List<Map.Entry<String, String>> companyFounderListEntry = 
				new ArrayList<Map.Entry<String, String>>(companyFounderSet);

		// sort list of entries using Collections class'
		// utility method sort(ls, cmptr)
		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());
			}
		});

		// store into LinkedHashMap for maintaining insertion order
		Map<String, String> companyFounderLHMap = 
				new LinkedHashMap<String, String>();

		// iterating list and storing in LinkedHahsMap
		for(Map.Entry<String, String> map : companyFounderListEntry){
			companyFounderLHMap.put(map.getKey(), map.getValue());
		}

		System.out.println("\n\nSorting HashMap by its Values"
				+ " in Ascending-order\n");

		// 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 : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Apple		Value : Tim Cook
Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison
Key : Facebook		Value : Mark Zuckerberg


Sorting HashMap by its Values in Ascending-order

Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison
Key : Facebook		Value : Mark Zuckerberg
Key : LinkedIn		Value : Reid Hoffman
Key : Google		Value : Sundar Pichai
Key : Apple		Value : Tim Cook

 

Example 2: Sorting in descending order of values:

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) {

		// creating HashMap object of type <String, String>
		HashMap<String, String> companyFounder = 
				new HashMap<String, String>(); 

		// adding key-value pairs to HashMap object
		companyFounder.put("Google", "Sundar Pichai");
		companyFounder.put("Facebook", "Mark Zuckerberg");
		companyFounder.put("LinkedIn", "Reid Hoffman");
		companyFounder.put("Apple", "Tim Cook");
		companyFounder.put("Microsoft", "Bill Gates");
		companyFounder.put("Amazon", "Jeff Bezos");
		companyFounder.put("Oracle", "Larry Ellison");

		System.out.println("Before Sorting for Values "
				+ "as per Insertion-Order\n");

		// 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());
		}

		// get entrySet from HashMap object
		Set<Map.Entry<String, String>> companyFounderSet = 
				companyFounder.entrySet();

		// convert HashMap to List of Map entries
		List<Map.Entry<String, String>> companyFounderListEntry = 
				new ArrayList<Map.Entry<String, String>>(companyFounderSet);

		// sort list of entries using Collections class'
		// utility method sort(ls, cmptr)
		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());
			}
		});

		// store into LinkedHashMap for maintaining insertion order
		Map<String, String> companyFounderLHMap = 
				new LinkedHashMap<String, String>();

		// iterating list and storing in LinkedHahsMap
		for(Map.Entry<String, String> map : companyFounderListEntry){
			companyFounderLHMap.put(map.getKey(), map.getValue());
		}

		System.out.println("\n\nSorting HashMap by its Values"
				+ " in Descending-Order\n");

		// 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 : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Apple		Value : Tim Cook
Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison
Key : Facebook		Value : Mark Zuckerberg


Sorting HashMap by its Values in Descending-Order

Key : Apple		Value : Tim Cook
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Facebook		Value : Mark Zuckerberg
Key : Oracle		Value : Larry Ellison
Key : Amazon		Value : Jeff Bezos
Key : Microsoft		Value : Bill Gates

 

Important points:

  • HashMap stores entries (Key/Value pairs) in random-order
  • LinkedHashMap stores entries (Key/Value pairs) as per insertion-order
  • TreeMap stores entries (Key/Value pairs) in sorted-order (sorted order of keys and not values)

 

References:

 

Happy Coding !!
Happy Learning !!

Sorting HashMap by Keys and Values using stream in Java 8
Converting Unordered HashMap into Sorted TreeMap