Java 8 – Sorting HashMap by Keys and Values using Stream

In this article, we will discuss how to sort HashMap by its Keys and Values using stream in Java 8

Prior to Java 8 release, we can sort HashMap either by its Keys or Values as explained in the below articles,

With the release of Java 8, we can use sorted() method of Stream class by passing Comparator objects

1. Sorting HashMap by its Keys

  • Use comparingByKey() method of Map.Entry clas which returns Comparator object to compare Map entry by its keys

HashMapSortingByKeyInJava8.java

package in.bench.resources.java.collection.map;

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

public class HashMapSortingByKeyInJava8 {

	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("LinkedIn", "Reid Hoffman");
		companyFounder.put("Apple Inc", "Tim Cook");
		companyFounder.put("Microsoft", "Bill Gates");
		companyFounder.put("Amazon", "Jeff Bezos");
		companyFounder.put("Oracle", "Larry Ellison");


		// 1.2 print to console
		System.out.println("Before Sorting for Keys:\n");


		// 1.3 iterating original HashMap
		for(Map.Entry<String, String> mvalue : companyFounder.entrySet()){
			System.out.println("Key : "  + mvalue.getKey() + "\t\t"
					+ "Value : "  + mvalue.getValue());
		}


		// 2. print to console
		System.out.println("\n\nSorting Keys using stream in Java 8\n");


		// 2.1 create LinkedhashMap for storing entries
		Map<String, String> keyLHMap = new LinkedHashMap<>();


		// 2.2 Sorting by Keys using comparingByKey() method
		companyFounder.entrySet().stream().sorted(
				Map.Entry.comparingByKey()).forEachOrdered(
						c -> keyLHMap.put(c.getKey(), c.getValue()));


		// 2.3 iterating LinkedHashMap in normal way
		for(Map.Entry<String, String> keyEntry : keyLHMap.entrySet()){
			System.out.println("Key : "  + keyEntry.getKey() + "\t\t"
					+ "Value : "  + keyEntry.getValue());
		}
	}
}

Output:

Before Sorting for Keys:

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


Sorting Keys using stream in Java 8

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

2. Sorting HashMap by its Values

  • Use comparingByValue() method of Map.Entry class which returns Comparator object to compare Map entry by its values

HashMapSortingByValueInJava8.java

package in.bench.resources.java.collection.map;

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

public class HashMapSortingByValueInJava8 {

	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("LinkedIn", "Reid Hoffman");
		companyFounder.put("Apple Inc", "Tim Cook");
		companyFounder.put("Microsoft", "Bill Gates");
		companyFounder.put("Amazon", "Jeff Bezos");
		companyFounder.put("Oracle", "Larry Ellison");


		// 1.2 print to console
		System.out.println("Before Sorting for Values:\n");


		// 1.3 iterating original HashMap
		for(Map.Entry<String, String> mkey : companyFounder.entrySet()){
			System.out.println("Key : "  + mkey.getKey() + "\t\t"
					+ "Value : "  + mkey.getValue());
		}


		// 2. print to console
		System.out.println("\n\nSorting Values stream in Java 8:\n");


		// 2.1 create LinkedhashMap for storing entries
		Map<String, String> valueLHMap = new LinkedHashMap<>();


		// 2.2 Sorting by Keys using comparingByValue() method
		companyFounder.entrySet().stream().sorted(
				Map.Entry.comparingByValue()).forEachOrdered(
						c -> valueLHMap.put(c.getKey(), c.getValue()));


		// 2.3 iterating LinkedHashMap in normal way
		for(Map.Entry<String, String> valueEntry : valueLHMap.entrySet()){
			System.out.println("Key : "  + valueEntry.getKey() + "\t\t"
					+ "Value : "  + valueEntry.getValue());
		}
	}
}

Output:

Before Sorting for Values:

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


Sorting Values stream in Java 8:

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 Inc		Value : Tim Cook

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:

Happy Coding !!
Happy Learning !!

Java - Sorting Hashtable contents
Java - Sorting HashMap by Keys and Values