Java 8 – How to Sort HashMap entries by its Keys ?

In this article, we will discuss how to sort HashMap entries by its Keys in ascending & descending order using Java 8

Before proceeding with this sorting examples understand below items,

1. Map.Entry.comparingByKey() method

  • Returns a comparator that compares Map.Entry in natural order on key
  • The returned comparator is serializable and throws NullPointerException when comparing an entry with a null key
  • Method signature :- static <K extends Comparable<? super K>,V> Comparator<Map.Entry<K,V>> comparingByKey()

1.1 Sorting HashMap by its Key in Ascending order

  • A HashMap contains 7 entries with Keys being in String type
  • We are sorting these Map Keys in alphabetical order using Java 8 Stream’s sorted() method and passing Map.Entry.comparingByKey() comparator as argument to sorted() method

SortHashMapByKeysInAscending.java

package net.bench.resources.stream.sort.hashmap;

import java.util.HashMap;
import java.util.Map;

public class SortHashMapByKeysInAscending {

	public static void main(String[] args) {

		// 1. creating HashMap object of type <String, Integer>
		Map<String, Integer> mnc = new HashMap<>(); 


		// 1.1 adding key-value pairs to HashMap object
		mnc.put("HCL", 3);
		mnc.put("LTI", 7);
		mnc.put("Cogni", 6);
		mnc.put("TCS", 1);
		mnc.put("TechM", 5);
		mnc.put("Infy", 2);
		mnc.put("Wipro", 4);


		// 1.2 print - before sorting - random order
		System.out.println("Before Sorting :- \n");


		// 1.3 print Map entries to console
		mnc.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));


		// 2. Sorting according to alphabetical order of Keys
		System.out.println("\n\nSorting according to alphabetical order of Keys :- \n");


		// 2.1 sorting by Map keys in ascending order
		mnc
		.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByKey())
		.forEach(entry -> System.out.println(
				"Key : " + entry.getKey()  + "\t\t"  + "Value : "  + entry.getValue()
				));
	}
}

Output:

Before Sorting :- 

Key : HCL		Value : 3
Key : LTI		Value : 7
Key : Wipro		Value : 4
Key : Cogni		Value : 6
Key : TCS		Value : 1
Key : TechM		Value : 5
Key : Infy		Value : 2


Sorting according to alphabetical order of Keys :- 

Key : Cogni		Value : 6
Key : HCL		Value : 3
Key : Infy		Value : 2
Key : LTI		Value : 7
Key : TCS		Value : 1
Key : TechM		Value : 5
Key : Wipro		Value : 4

2. Map.Entry.comparingByKey(Comparator) method

  • Returns a comparator that compares Map.Entry by key using the given Comparator
  • The returned comparator is serializable if the specified comparator is also serializable
  • Method signature :- static <K,V> Comparator<Map.Entry<K,V>> comparingByKey(Comparator<? super K> cmp)

2.1 Sorting HashMap by its Key in Descending order

  • A HashMap contains 7 entries with Keys being in String type
  • We are sorting these Map Keys in reverse alphabetical order using Java 8 Stream’s sorted() method and passing Map.Entry.comparingByKey(Comparator.reverseOrder()) comparator as argument to sorted() method

SortHashMapByKeysInDescending.java

package net.bench.resources.stream.sort.hashmap;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class SortHashMapByKeysInDescending {

	public static void main(String[] args) {

		// 1. creating HashMap object of type <String, Integer>
		Map<String, Integer> mnc = new HashMap<>(); 


		// 1.1 adding key-value pairs to HashMap object
		mnc.put("HCL", 3);
		mnc.put("LTI", 7);
		mnc.put("Cogni", 6);
		mnc.put("TCS", 1);
		mnc.put("TechM", 5);
		mnc.put("Infy", 2);
		mnc.put("Wipro", 4);


		// 1.2 print - before sorting - random order
		System.out.println("Before Sorting :- \n");


		// 1.3 print Map entries to console
		mnc.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));


		// 2. Sorting according to alphabetical order of Keys
		System.out.println("\n\nSorting according to "
				+ "reverse alphabetical order of Keys :- \n");


		// 2.1 sorting by Map keys in ascending order
		mnc
		.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
		.forEach(entry -> System.out.println(
				"Key : " + entry.getKey()  + "\t\t"  + "Value : "  + entry.getValue()
				));
	}
}

Output:

Before Sorting :- 

Key : HCL		Value : 3
Key : LTI		Value : 7
Key : Wipro		Value : 4
Key : Cogni		Value : 6
Key : TCS		Value : 1
Key : TechM		Value : 5
Key : Infy		Value : 2


Sorting according to reverse alphabetical order of Keys :- 

Key : Wipro		Value : 4
Key : TechM		Value : 5
Key : TCS		Value : 1
Key : LTI		Value : 7
Key : Infy		Value : 2
Key : HCL		Value : 3
Key : Cogni		Value : 6

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 8 – How to Sort HashMap entries by its Values ?
Java 8 - Sorting list of objects on multiple fields