Java 8 Stream - Sort HashMap based on Keys and Values

By default, Java HashMap doesn’t maintain any order. However, if you need to sort the HashMap, we sort the HashMap explicitly based on your requirements. So, in this section, let’s understand how to sort the hashmap according to the keys and values by using Java 8’s Stream API.

1. Sort HashMap by keys in natural order

import java.util.*;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(44, "Java");
map.put(66, "Ada");
map.put(29, "Go");
map.put(98, "Kotlin");
map.put(11, "C");
map.put(125, "Rust");

Map<Integer, String> sortedMap
= map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

System.out.println("Before Sorting : ");
System.out.println(map);

System.out.println("After Sorting : ");
System.out.println(sortedMap);

}
}

Console Output:

Before Sorting : 

{66=Ada, 98=Kotlin, 11=C, 44=Java, 29=Go, 125=Rust}

After Sorting : 

{11=C, 29=Go, 44=Java, 66=Ada, 98=Kotlin, 125=Rust}

  • The entrySet() method returns a set of the same elements as in the hash map. It returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in this map.
  • You can use the stream() method to return this returned set as a Stream of Key-Value Pairs.
  • In the Map.Entry class, there is a static method comparingByKey(). This method returns the Comparator that compares the Map entries according to the order of the keys.
  • .sorted(Map.Entry.comparingByKey()) sorts the elements of the Stream by the keys of the entries.
  • Collect and return a new LinkedHashMap. LinkedHashMap  maintains and tracks the order of insertion where elements can be inserted and accessed in their order.


2. Sort HashMap in descending order or reverse order of keys

Use Comparator.reverseOrder() to sort HashMap by key in descending Order, or reverse Order.

import java.util.*;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(44, "Java");
map.put(66, "Ada");
map.put(29, "Go");
map.put(98, "Kotlin");
map.put(11, "C");
map.put(125, "Rust");

Map<Integer, String> sortedMap
= map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

System.out.println("Before Sorting : ");
System.out.println(map);

System.out.println("After Sorting : ");
System.out.println(sortedMap);

}
}

Console Output:

Before Sorting : 

{66=Ada, 98=Kotlin, 11=C, 44=Java, 29=Go, 125=Rust}

After Sorting : 

{125=Rust, 98=Kotlin, 66=Ada, 44=Java, 29=Go, 11=C}


3. Sort HashMap by values in natural order

import java.util.*;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(44, "Java");
map.put(66, "Ada");
map.put(29, "Go");
map.put(98, "Kotlin");
map.put(11, "C");
map.put(125, "Rust");

Map<Integer, String> sortedMap
= map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

System.out.println("Before Sorting : ");
System.out.println(map);

System.out.println("After Sorting : ");
System.out.println(sortedMap);

}
}

Console Output:

Before Sorting : 

{66=Ada, 98=Kotlin, 11=C, 44=Java, 29=Go, 125=Rust}

After Sorting : 

{66=Ada, 11=C, 29=Go, 44=Java, 98=Kotlin, 125=Rust}

.sorted(Map.Entry.comparingByValue()) sorts the elements of the Stream by the values of the entries.


4. Sort HashMap in reverse order of values

Use Comparator.reverseOrder() to sort HashMap by values in reverse Order.

import java.util.*;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(44, "Java");
map.put(66, "Ada");
map.put(29, "Go");
map.put(98, "Kotlin");
map.put(11, "C");
map.put(125, "Rust");

Map<Integer, String> sortedMap
= map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

System.out.println("Before Sorting : ");
System.out.println(map);

System.out.println("After Sorting : ");
System.out.println(sortedMap);

}
}

Console Output:

Before Sorting : 

{66=Ada, 98=Kotlin, 11=C, 44=Java, 29=Go, 125=Rust}

After Sorting : 

{125=Rust, 98=Kotlin, 44=Java, 29=Go, 11=C, 66=Ada}

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete