Sorting HashMap by Keys and Values using stream in Java 8

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

Sorting HashMap by its Keys in Java 1.8

  • use comparingByKey() method of Map.Entry class
  • which returns comparator object to compare Map entry by its keys

Sorting HashMap by its Values in Java 1.8

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

 

Key Sorting:

Example 1: Sorting HashMap by its keys using stream in Java 8

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

		// 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 Keys:\n");

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

		// create LinkedhashMap for storing entries 
		// after SORTING by Keys using Stream in Java 8
		Map<String, String> keyLHMap = new LinkedHashMap<>();

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

		System.out.println("\n\nSorting Keys using stream in Java 8\n");

		// 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 : 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 Keys using stream in Java 8

Key : Amazon		Value : Jeff Bezos
Key : Apple		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

 

 

Value Sorting:

Example 2: Sorting HashMap by its values using stream in Java 8

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

		// 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:\n");

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

		// create LinkedhashMap for storing entries 
		// after SORTING by Values using Stream in Java 8
		Map<String, String> valueLHMap = new LinkedHashMap<>();

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

		System.out.println("\n\nSorting Values stream in Java 8:\n");

		// 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 : 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 Values using 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		Value : Tim Cook

 

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 sorting-order (sorted order of keys and not values)

 

References:

 

Happy Coding !!
Happy Learning !!

Sorting Hashtable contents
Sorting HashMap by Keys and Values