Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

How to Sort a Java Map by Value

In this article, we will learn to sort elements of Java Map. Map in java is unsorted by default and stores data in key-value format. It is very much required to sort them based on the values to make decisions based on values.

Example: Sort a Map

Here, we are having an example of a Map of students with their names and heights in centimeters. Let's say we want to sort students based on their names (programmatically based on keys) for that we will use Collections.sort() method, the same method can be also used to sort students based on their heights (programmatically based on values) but the only change required is the comparator function.

The Collections.sort() always take a List<T> as a parameter. So, we will create a list from Map.entrySet() this method that will return all key-value pairs of the map. Comparator function comes into play when sorting the particular set depends on multiple parameters. Inside the comparator function, return student1.getKey().compareTo(student2.getKey()); decides the way of sorting. In this case, it will sort based on keys.

import java.util.*;
public class StudyTonight
{
    public static void main(String args[])
    {
        Map<String,Integer> students = new HashMap<>();            

        students.put("Student 1", 159);
        students.put("Student 2", 147);
        students.put("Student 3", 183);
        students.put("Student 4", 167);
        students.put("Student 5", 173);

        List<Map.Entry<String, Integer>> student_list = new ArrayList<>(students.entrySet());
       
        System.out.println("\nBefore Sorting\n");
        for(Map.Entry<String, Integer> student: student_list)
        {
            System.out.println(student.getKey()+" "+student.getValue());
        }
        
        Collections.sort(student_list, new Comparator<Map.Entry<String, Integer>>()
        {
            @Override
            public int compare(Map.Entry<String, Integer> student1, Map.Entry<String, Integer> student2){
                return student1.getKey().compareTo(student2.getKey());
            }
        });

        System.out.println("\nAfter Sorting\n");
        for(Map.Entry<String, Integer> student: student_list)
        {
            System.out.println(student.getKey()+" "+student.getValue());
        }             
            
    }
}


Before Sorting
Student 2 147
Student 1 159
Student 4 167
Student 3 183
Student 5 173
After Sorting
Student 1 159
Student 2 147
Student 3 183
Student 4 167
Student 5 173

Example of Sorting a Map, Based on Values

To sort the Map based on values we need to simply change the comparator function student1.getValue().compareTo(student2.getValue()); and the rest code will be the same.

enlightened Here, the comparator function is dealing with values of Map, and therefore we will get the result based on values.

import java.util.*;
public class StudyTonight
{
    public static void main(String args[])
    {
        Map<String,Integer> students = new HashMap<>();            

        students.put("Student 1", 159);
        students.put("Student 2", 147);
        students.put("Student 3", 183);
        students.put("Student 4", 167);
        students.put("Student 5", 173);

        List<Map.Entry<String, Integer>> student_list = new ArrayList<>(students.entrySet());
       
        System.out.println("\nBefore Sorting\n");
        for(Map.Entry<String, Integer> student: student_list)
        {
            System.out.println(student.getKey()+" "+student.getValue());
        }
        
        Collections.sort(student_list, new Comparator<Map.Entry<String, Integer>>()
        {
            @Override
            public int compare(Map.Entry<String, Integer> student1, Map.Entry<String, Integer> student2){
                return student1.getValue().compareTo(student2.getValue());
            }
        });

        System.out.println("\nAfter Sorting\n");
        for(Map.Entry<String, Integer> student: student_list)
        {
            System.out.println(student.getKey()+" "+student.getValue());
        }             
            
    }
}


Before Sorting
Student 2 147
Student 1 159
Student 4 167
Student 3 183
Student 5 173
After Sorting
Student 2 147
Student 1 159
Student 4 167
Student 5 173
Student 3 183

Example of Sorting Map Using lambda and Based on Values

This method is also very much similar to what we did in the first example. But, the only difference is in the comparator function which is known as anonymous implementation (student1, student2)->student1.getKey().compareTo(student2.getKey()));

import java.util.*;
public class StudyTonight
{

    public static void main(String args[])
    {
        Map<String,Integer> students = new HashMap<>();            

        students.put("Student 1", 159);
        students.put("Student 2", 147);
        students.put("Student 3", 183);
        students.put("Student 4", 167);
        students.put("Student 5", 173);

        List<Map.Entry<String, Integer>> student_list = new ArrayList<>(students.entrySet());
       
        System.out.println("\nBefore Sorting\n");
        for(Map.Entry<String, Integer> student: student_list)
        {
            System.out.println(student.getKey()+" "+student.getValue());
        }
        
        Collections.sort(student_list, (student1, student2)->student1.getKey().compareTo(student2.getKey())); 
    
        System.out.println("\nAfter Sorting\n");
        for(Map.Entry<String, Integer> student: student_list)
        {
            System.out.println(student.getKey()+" "+student.getValue());
        }             
            
    }
}


Before Sorting
Student 2 147
Student 1 159
Student 4 167
Student 3 183
Student 5 173
After Sorting
Student 1 159
Student 2 147
Student 3 183
Student 4 167
Student 5 173

Conclusion:

We can sort Map in Java by using Collection.sort() method with the help of the comparator function. The comparator function can be implemented in an anonymous way which is more efficient.