• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us

How to Sort a Map by Value in Java

March 8, 2024 //  by Anees Asghar

A map in Java keeps the data in the key-value pair format. These key-value pairs are known as map entries. A map contains only unique keys while the values can be repeated. It keeps the data entries in the order in which they are put/inserted. However, you can sort them later on according to your preferences. For this purpose, different methods are used that will be explored in this Java blog along with examples.

Sorting a Map by Values in Java

As discussed earlier, a map in Java stores data in key-value pair format. You can sort a Java map by keys as well as values. To sort a map by values in Java, employ one of the following methods:

  • Method 1: Using Collections.sort() With comparingByValue()
  • Method 2: Using stream().sorted()
  • Method 3: Using Custom Comparator

So, let’s get started with the sort() method.

Method 1: Sorting a Map By Values in Java Using the Collections.sort() With comparingByValue()

The “Collections.sort()” is a static method of the “java.util.Collections” class. It sorts the elements of the list in ascending order. You can invoke this method on all List data structures, such as List, LinkedList, etc. To use this method on a map to sort it by values, use it along with the “comparingByValue()” method. 

Let’s understand it via the following examples:

Example 1: Sorting a Map by Values in Natural/Ascending Order Using sort()

First, import all the essential classes from the “java.util” package using the following statement: 

import java.util.*;

Also, import the Entry class that will be used later in this program:

import java.util.Map.Entry;

Now let’s create a map to be sorted, and name it “authorsInfo”:

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

After this, invoke the put() method on the declared map to initialize it with key-value pairs:

authorsInfo.put("Anees", 12);
authorsInfo.put("Asghar", 6);
authorsInfo.put("Joseph", 5);
authorsInfo.put("John", 8);
authorsInfo.put("David", 15);

Let’s traverse the map via forEach() and print it on the console:

System.out.println("The Original Map: ");
authorsInfo.forEach((key,val)->System.out.println(key + " ==> " + val));

Now use the entrySet() method to get a set view of all the entries(key-value pairs) of a hashmap. Also, create a list and store the elements/entries retrieved by the entrySet() method in it: 

List<Entry<String, Integer>> authorsList = new ArrayList<>(authorsInfo.entrySet());

Up next, invoke the sort() along with the comparingByValue() method of the “Map.Entry” class to sort the given map by value:

authorsList.sort(Entry.comparingByValue());

Finally, print the sorted map(by values) using the following lines of code:

System.out.println("The Sorted Map: ");
authorsList.forEach(System.out::println);

The output snippet verifies that the given map has been sorted by values successfully:

Example 2: Sorting a Map by Values in Reverse/Descending Order Using sort()

To sort a map by value in descending/reverse order, you need to pass an additional “comparator” argument to the sort() method. 

For example, replacing the line “authorsList.sort(Entry.comparingByValue())” of example 1 with the following code will sort the map by value in reverse order:

authorsList.sort(Entry.comparingByValue(Comparator.reverseOrder()));

The below snippet demonstrates that the map has been sorted(by values) successfully in reverse order:

Method 2: Sorting a Map By Values in Java Using stream().sorted()

Stream API facilitates us with a handy method named “sorted()”. It retrieves a stream of sorted(in natural order) elements. It is used with the help of several other methods, such as “entrySet()”, “comparingByValue()”, etc. 

Example 1: Sorting a Map by Values in Natural/Ascending Order Using sorted()

First, import the built-in classes that will be used to sort the map by value:

import java.util.*;
import java.util.stream.Stream;

After this, create a map that you want to sort (we will use the same map that we used in the previous section). Also, use the “stream().sorted()” with the “comparingByValue()” method to sort/arrange the given map by value:

Stream<Map.Entry<String, Integer>> sortedMap = authorsInfo.entrySet().stream().sorted(Map.Entry.comparingByValue());

Here, the stream() method converts the map’s entrySet (authorsInfo) into a stream of entries. While the sorted() method sorts the converted stream in ascending/natural order.

Now, let’s traverse each element of the sorted map using the forEach() method and print them on the console:

System.out.println("The Sorted Map: ");
sortedMap.forEach(System.out::println);

There you go! The stated method has successfully arranged the given map in ascending/increasing order:

Example 2: Sorting a Map by Values in Reverse/Descending Order Using sorted()

To sort a map by value in reverse order, you can execute the sorted() method with the “reverseOrder()” method:

Stream<Map.Entry<String, Integer>> sortedMap = authorsInfo.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()));

In this code, we pass the “Comparator.reverseOrder()” as an argument to the comparingByValue() to get the desired output:

Method 3: Sorting a Map By Values in Java Via Custom Comparator

You can also sort a map(by value) by creating a custom comparator. For this, simply create a comparator object and specify a map as its instance variable. Here is a step-by-step demonstration of the custom comparator to sort a map by value.

First, create a comparator “SortByComparator” to define custom sorting criteria. Within this class, create a map and a constructor; pass the given map to the constructor as a parameter. Also, create a method that returns 1 if the given/compared objects are equal. Up next, use the compareTo() method to compare and sort the map by values:

import java.util.*;

public class SortMapByValue {
  public static class SortByComparator implements Comparator<Object> {
Map<String, Integer> sortedMap;
      public SortByComparator(Map<String, Integer> sortedMap) {
this.sortedMap = sortedMap;
}
       public int compare(Object obj1, Object obj2) {
    if (sortedMap.get(obj1) == sortedMap.get(obj2))
  return 1;
return ((Integer) sortedMap.get(obj1)).compareTo((Integer) sortedMap.get(obj2));
}
}
public static void main(String[] args) {
  Map<String, Integer> authorsInfo = new HashMap<>();
  authorsInfo.put("Anees", 12);
  authorsInfo.put("Asghar", 6);
  authorsInfo.put("Joseph", 5);
  authorsInfo.put("John", 8);
  authorsInfo.put("David", 15);
         System.out.println("The Original Map: ");
  authorsInfo.forEach((key,val)-> System.out.println(key + " ==> " + val));
            Map<String, Integer> resultantMap = new TreeMap<>(new SortByComparator(authorsInfo));
  resultantMap.putAll(authorsInfo);
           System.out.println("The Sorted Map: ");
  resultantMap.forEach((key, val) -> System.out.println(key + " ==> " + val));
}
}

In the main() method, create and initialize a map that needs to be sorted. After this, create a treemap and pass the custom comparator “SortByComparator” as its argument. Also, use the putAll() method to pass all entries of the “authorsInfo” map into “resultantMap” to perform a comparison. Finally, print the sorted map on the console:

That’s all about sorting a map by value in Java.

Conclusion

In Java, you can sort a map by value using three methods: “Collections.sort()”, “Stream().sorted()”, and “Custom Comparators”. The “Collections.sort()” and “Stream().sorted()” are built-in methods that are used with the comparingByValue() method to sort the map by value in natural/ascending order(by default). If you want to sort a map in reverse/descending order, use the “Comparator.reverseOrder()” with the sort() or sorted() method. 

Alternatively, you can customize your own logic to sort a map by value using the Comparator interface. This guide has illustrated all these methods alongside practical examples.

Category: Java

About Anees Asghar

Anees, a go-to expert of various technologies like PostgreSQL, Java, JS, and Linux. He has been contributing to the community through his words. A passion for serving the people excites him to craft primo content.

Previous Post: « How to Use StringUtils Class in Java
Next Post: How to Format a String With printf() in Java »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Initialize an Array in Java

Introduction to Java Server Faces (JSF)

Introduction to Java 6.0 New Features, Part–1

Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

Introduction to Java Server Faces(JSF) HTML Tags

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact