Sorting Java Map by Values

JavaJavaBeginner
Practice Now

Introduction

In Java, Maps are unsorted by default and stores data in key-value format. It is often required to sort them based on the values to make decisions based on values. In this step-by-step lab, we will learn how to sort a Java Map based on the values.

Creating a Map in Java

First, we will create a Map of students with their names and heights in centimeters to understand how to sort maps in Java.

import java.util.*;

public class MapSortingDemo {
    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);
    }
}

Sorting a Map Based on Values

To sort the Map based on values, we need to create a List from Map.entrySet(). This method returns all the key-value pairs from the Map. Comparator function comes into play when sorting a particular set depends on multiple parameters. In the comparator function, return student1.getValue().compareTo(student2.getValue()); decides the way of sorting, i.e., by value, and this will sort the Map based on values.

List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());

Collections.sort(studentList, 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());
    }
});

Display Sorted Map Based on Values

Display the sorted Map in the console.

for (Map.Entry<String, Integer> student : studentList) {
    System.out.println(student.getKey() + " " + student.getValue());
}

Sorting Map Using Lambda Expression

We can also sort a Map based on values using Lambda Expressions, which is a shorter and more efficient way.

List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());

studentList.sort((student1, student2) -> student1.getValue().compareTo(student2.getValue()));

Display Sorted Map Based on Values with Lambda Expression

Display the sorted Map in the console.

studentList.forEach(student -> System.out.println(student.getKey() + " " + student.getValue()));

Sorting Map Based on Keys

Similarly, we can sort the Map based on keys. In the comparator function, return student1.getKey().compareTo(student2.getKey()); decides the way of sorting, i.e., by key.

List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());

Collections.sort(studentList, 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());
    }
});

Display Sorted Map Based on Keys

Display the sorted Map in the console.

for (Map.Entry<String, Integer> student : studentList) {
    System.out.println(student.getKey() + " " + student.getValue());
}

Sorting Map Based on Keys using Lambda Expression

We can also sort a Map based on keys using Lambda Expressions, which is a shorter and more efficient way.

List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());

studentList.sort((student1, student2) -> student1.getKey().compareTo(student2.getKey()));

Display Sorted Map Based on Keys using Lambda Expression

Display the sorted Map in the console.

studentList.forEach(student -> System.out.println(student.getKey() + " " + student.getValue()));

Summary

In this lab, we learned how to sort a Java Map based on values using Collections.sort() method and Comparator functions, as well as using Lambda Expressions. We also learned how to sort a Map based on keys. Sorting a Map based on values can be useful in many situations, such as ranking or priority-based operations.

Other Java Tutorials you may like