Java

How to Sort a Map by Value in Java

In Java, “Maps” are a powerful data structure used for storing data. A map can easily determine the appropriate value for a given key because the map stores data in Key-value pairs, where each key has a corresponding unique value. To retrieve these values from a map, a unique key is required; however, the values can be the same for two unique keys.

This article will explain the method of sorting a map by value in Java.

How to Sort a Map by Value in Java?

In Java, a map can be sorted by value:

  • Using sort() method
  • Using sorted() method

We will now check out each of the mentioned methods one by one!

Method 1: Sort a Map by Value in Java Using sort() Method

The “sort()” method is a static method of the Java Collection class. This method can only be applied to lists such as LinkedList, ArrayList, and so on.

This section will demonstrate the method to sort the values of map elements in ascending and descending order.

Example 1: Sort a Map by Value in Ascending Order

In this example, we will sort the values of the map in ascending order using the “comparingByValue()” and the “sort()”. We will first create an integer-type map called “map” as follows:

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

 

Then, we put the values to the created map in the form of key-value pairs:

map.put(7, 10);
map.put(1, 1000);
map.put(5, 380);
map.put(3, 700);

 

Print the map as a key-value pair using the “forEach” loop. The forEach loop is only being utilized for looping through each element in the Map repeatedly. We have added a “lambda expression” (->) with the loop to avoid multiple lines in source code:

map.forEach((k,v)->System.out.println(k + ":" + v));

 

Then, we will print the following statement using the “System.out.println()” method:

System.out.println("The values after Sorting:");

 

To sort the entries with the “sort()” method, we must first create a list with the set of entries returned by the “entrySet()” method:

List<Entry<Integer, Integer>> nlist = new ArrayList<>(map.entrySet());

 

Now, we will call the sort() method by passing the “comparingByValue()” method as an argument to allow comparison of the entry’s values:

nlist.sort(Entry.comparingByValue());

 

Lastly, we will print the sorted values of the map using the forEach loop:

nlist.forEach(System.out::println);

 

Note: While executing the above example, you must import the libraries related to Map, List, ArrayList, MapEntry, HashMap at the top of the source code.

The output shows the map is sorted by value in ascending order:

Example 2: Sort a Map by Value in Descending Order

In this example, we will sort the values of a map using the “sort()” method and “comparingByValue()” method to sort the elements of the map in descending order. Here, first, we will create an integer type map to store int values:

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

 

Then, we will add the data in a map in the form of key-value pairs:

map.put(7, 10);
map.put(1, 100);
map.put(5, 3800);
map.put(3, 70);

 

We will create a List to sort the map elements:

List<Entry<Integer, Integer>> nlist = new ArrayList<>(map.entrySet());

 

Here, we will call the “comparingByValue()” method by passing a “reverseOrder()” method of the “Comparator” class as an argument. It will return the map values in reverse order:

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

 

Print the sorted values by using “forEach” loop:

nlist.forEach(System.out::println);

 

As you can see the map values are sorted in the descending order:

Let’s see another method for sorting map elements by value.

 

Method 2: Sort a Map by Value in Java Using sorted() Method

The second approach is to sort the map by values using the Stream API. The Stream API contains a number of methods that can be used to process an object collection, such as stream() and sorted().

In this section, we will also print the map by values in both ascending and descending order.

Example 1: Sort a Map by Value in Ascending Order

This example will use the same map value and sort them in ascending order using the “sorted()” method of Stream API. We will utilize the “stream()” method to turn the Map’s entrySet into a stream and then sort the map using the “sorted()” method.

The “comparingByValue()” method of the Map provides the “sorted()” method with additional information about the natural sorting order. Lastly, the “forEach” loop can be used to access all of the elements and get the key-value pairs one by one:

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

 

The output shows the map is sorted by value in ascending order using the sorted() method:

Example 2: Sort a Map by Value in Descending order

To sort the map by value in descending order, we will use the “comparingByValue()” method by passing “reverseOrder()” method as an argument to the “sorted()” method:

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

 

As you can see, the “sorted()” method arranged the value of the map in descending order:

We have provided all the essential information related to sorting a map by value.

Conclusion

For sorting a map by value in Java, use the “sort()” method and the “sorted()” method with the comparingByValue() method. These methods sort the values in ascending order, while for descending order, you must call the reverseOrder() method of the Comparator class as an argument of the specified methods. This article covered various Java methods for sorting a map by value.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.