Java 8 Map Sorting Example
Hello readers, in this tutorial, we will learn how to Sort a Map using Java8 Stream’s API and Lambda expression.
1. Introduction
These days in the programming universe sorting a map is one of the most habitual tasks in Java. In the ancient Java world, developers could sort a Map either by its keys or values. In Java8, JDK developers have introduced in new sorted()
method in Stream class. To sort the elements, developers can use the sorted()
method of the Stream’s API by passing the comparator object.
1.1 Sorting a Map by Key
In order to sort the key elements of a Map, developers use the comparingByKey()
method of the Map.Entry
class. This method returns the ‘key‘ elements in an ascending order.
1.2 Sorting a Map by Value
In order to sort the value elements of a Map, developers use the comparingByValue()
method of the Map.Entry
class. This method returns the ‘value‘ elements in an ascending order.
In case developers want to sort the ‘key’ or ‘value’ elements in a reverse order they will have to use the Collections.reverseOrder()
method. Now, open up the Eclipse Ide and we will go over these methods to sort a map using the Java Stream and Lambda expression.
2. Java8 Map Sorting Example
2.1 Tools Used
We are using Eclipse Oxygen, JDK 1.8 and Maven.
2.2 Project Structure
Firstly, let’s review the final project structure in case you’re confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will show how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ check-box and just click on next button to proceed.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of the maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Java8MapSorting</groupId> <artifactId>Java8MapSorting</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> </project>
Developers can start adding the dependencies that they want. Let’s start building the application!
3. Application Building
Below are the steps involved in explaining this tutorial.
3.1 Java Class Implementation
Let’s create the required Java files. Right-click on the src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: com.jcg.java
.
Once the package is created in the application, we will need to create the implementation class to show the usage of Map.Entry.comparingByKey()
, Map.Entry.comparingByValue()
, and Collections.reverseOrder()
methods. Right-click on the newly created package: New -> Class
.
A new pop window will open and enter the file name as: Java8SortMapDemo
. The implementation class will be created inside the package: com.jcg.java
.
3.1.1 Example of Sorting a Map in Java8
Here is the complete Java program to sort a map using the Lambda Stream in Java8 programming.
Java8SortMapDemo.java
package com.jcg.java; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /* * A simple program that Sort a Map using Java8 Stream API and Lambda Expressions. * @author Batra, Yatin */ public class Java8SortMapDemo { public static void main(String[] args) { // Creating a Map object of type <String, String> and adding key-value pairs Map<String, String> ceo = new HashMap<String, String>(); ceo.put("Google", "Sundar Pichai"); ceo.put("Facebook", "Mark Zuckerberg"); ceo.put("Twitter", "Jack Dorsey"); ceo.put("Apple", "Tim Cook"); ceo.put("Microsoft", "Satya Nadella"); ceo.put("Amazon", "Jeff Bezos"); ceo.put("Oracle", "Mark Hurd"); ceo.put("SpaceX", "Elon Musk"); // Iterating Original Map System.out.println("Original Map: \n" + ceo); System.out.println(); // Method #1 - Sort Map by Key sortMapByKey(ceo); System.out.println(); // Method #2 - Sort Map by Value sortMapByValue(ceo); System.out.println(); // Method #3 - Sort Map by Key in Reverse Order sortMapByKeyInReverseOrder(ceo); System.out.println(); // Method #4 - Sort Map by Value in Reverse Order sortMapByValueInReverseOrder(ceo); } // Method #1 private static void sortMapByKey(Map<String, String> ceo) { // Creating LinkedhashMap for storing entries after SORTING by Keys using Stream in Java8 Map<String, String> keyMap = new LinkedHashMap<String, String>(); // Sorting by Keys using the 'comparingByKey()' method ceo.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(c -> keyMap.put(c.getKey(), c.getValue())); System.out.println("Map Sorted by Key: \n" + keyMap); } // Method #2 private static void sortMapByValue(Map<String, String> ceo) { // Creating LinkedhashMap for storing entries after SORTING by Values using Stream in Java8 Map<String, String> valueMap = new LinkedHashMap<String, String>(); // Sorting by Value using the 'comparingByValue()' method ceo.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEachOrdered(c -> valueMap.put(c.getKey(), c.getValue())); System.out.println("Map Sorted by Value: \n" + valueMap); } // Method #3 private static void sortMapByKeyInReverseOrder(Map<String, String> ceo) { // Creating LinkedhashMap for storing entries after SORTING by Keys using Stream in Java8 Map<String, String> keyRMap = new LinkedHashMap<String, String>(); // Sorting by Keys using the 'comparingByKey()' method ceo.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).forEachOrdered(c -> keyRMap.put(c.getKey(), c.getValue())); System.out.println("Map Sorted by Key in Reverse order: \n" + keyRMap); } // Method #4 private static void sortMapByValueInReverseOrder(Map<String, String> ceo) { // Creating LinkedhashMap for storing entries after SORTING by Values using Stream in Java8 Map<String, String> valueMap = new LinkedHashMap<String, String>(); // Sorting by Value using the 'comparingByValue()' method ceo.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).forEachOrdered(c -> valueMap.put(c.getKey(), c.getValue())); System.out.println("Map Sorted by Value in Reverse order: \n" + valueMap); } }
4. Run the Application
To run the application, developers need to right-click on the class, Run As -> Java Application
. Developers can debug the example and see what happens after every step!
5. Project Demo
The above code shows the following logs as output.
# Logs for 'Java8SortMapDemo' # =============================== Original Map: {Google=Sundar Pichai, Apple=Tim Cook, SpaceX=Elon Musk, Twitter=Jack Dorsey, Microsoft=Satya Nadella, Amazon=Jeff Bezos, Oracle=Mark Hurd, Facebook=Mark Zuckerberg} Map Sorted by Key: {Amazon=Jeff Bezos, Apple=Tim Cook, Facebook=Mark Zuckerberg, Google=Sundar Pichai, Microsoft=Satya Nadella, Oracle=Mark Hurd, SpaceX=Elon Musk, Twitter=Jack Dorsey} Map Sorted by Value: {SpaceX=Elon Musk, Twitter=Jack Dorsey, Amazon=Jeff Bezos, Oracle=Mark Hurd, Facebook=Mark Zuckerberg, Microsoft=Satya Nadella, Google=Sundar Pichai, Apple=Tim Cook} Map Sorted by Key in Reverse order: {Twitter=Jack Dorsey, SpaceX=Elon Musk, Oracle=Mark Hurd, Microsoft=Satya Nadella, Google=Sundar Pichai, Facebook=Mark Zuckerberg, Apple=Tim Cook, Amazon=Jeff Bezos} Map Sorted by Value in Reverse order: {Apple=Tim Cook, Google=Sundar Pichai, Microsoft=Satya Nadella, Facebook=Mark Zuckerberg, Oracle=Mark Hurd, Amazon=Jeff Bezos, Twitter=Jack Dorsey, SpaceX=Elon Musk}
That’s all for this post. Happy Learning!
6. Conclusion
In this tutorial, we had an in-depth look at the Java8 Map.Entry.comparingByKey()
, Map.Entry.comparingByValue()
, and Collections.reverseOrder()
methods for sorting a map. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you whatever you were looking for.
7. Download the Eclipse Project
This was an example of Sorting a Map in Java8.
You can download the full source code of this example here: Java8MapSorting