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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/method_overriding("`Method Overriding`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/annotation("`Annotation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/hashmap("`HashMap`") java/ProgrammingTechniquesGroup -.-> java/lambda("`Lambda`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/sorting("`Sorting`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/DataStructuresGroup -.-> java/collections_methods("`Collections Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/method_overriding -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/scope -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/annotation -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/arraylist -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/classes_objects -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/class_methods -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/hashmap -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/lambda -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/modifiers -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/oop -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/wrapper_classes -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/identifier -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/sorting -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/data_types -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/operators -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/output -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/strings -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/collections_methods -.-> lab-117453{{"`Sorting Java Map by Values`"}} java/system_methods -.-> lab-117453{{"`Sorting Java Map by Values`"}} end

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