How to Sort Map using Streams API

Introduction

Sorting a map of objects is a very common problem faced in Java. In this article, we will learn how to sort maps traditionally and then optimize them using Java 8 streams API.

Traditional Approach

For sorting a map using the traditional approach, we can simply convert it into EntrySet and use Collections.sort() methods

Code Example:-

public class SortMapWithoutStreams {

    public static void main(String[] args) {

        Map<String, Integer> map=new HashMap<>();
        map.put("eight", 8);
        map.put("four", 4);
        map.put("ten", 10);
        map.put("two", 2);

        List<Entry<String,Integer>> entries=new ArrayList<>(map.entrySet());
        Collections.sort(entries,new Comparator<Entry<String,Integer>>() {

            @Override
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                // TODO Auto-generated method stub
                return o1.getValue().compareTo(o2.getValue());
            }
        });

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

        //o/p:-
        //two 2
        //four 4
        //eight 8
        //ten 10
}
}

Streams Approach

For sorting a map using the streams approach, we can make use of the Comparator functional interface inside the sorted method for Java 8 streams.

Code Example:

public class SortMapWithStreams {
    public static void main(String[] args) {

        Map<String, Integer> map=new HashMap<>();
        map.put("eight", 8);
        map.put("four", 4);
        map.put("ten", 10);
        map.put("two", 2);

        map.entrySet().stream().sorted(Map.Entry.comparingByValue())
        .forEach(System.out::println);

        //o/p:-
        //two 2
        //four 4
        //eight 8
        //ten 10
    }
}

Real-world Example

Suppose there is a map of Employees and we want to apply custom sorting on that map, then Java 8 streams provide the most optimized and readable solution to sort it using the Comparator Functional Interface.

Code Example:-

Employee.java

public class Employee {

    private int id;
    private String name;
    private String dept;
    private long salary;

    //CONSTRUCTORS, GETTERS,SETTERS AND TOSTRING
    }

SortEmployeeMap.java

public class SortEmployeeMap {

    public static void main(String[] args) {

        Map<Employee,Integer> employeeMap=new HashMap<>();
        employeeMap.put(new Employee(176,"Roshan","IT",600000), 40);
        employeeMap.put(new Employee(388,"Bikash","Civil",900000), 80);
        employeeMap.put(new Employee(246,"Bikash","DEFENCE",700000), 60);
        employeeMap.put(new Employee(568,"Roshan","CORE",800000), 50);

        employeeMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey(Comparator.comparing(Employee::getName).reversed()
        .thenComparing(Employee::getSalary)))
        .forEach(System.out::println);

        //o/p:-
        //Employee [id=176, name=Roshan, dept=IT, salary=600000]=40
        //Employee [id=568, name=Roshan, dept=CORE, salary=800000]=50
        //Employee [id=246, name=Bikash, dept=DEFENCE, salary=700000]=60
        //Employee [id=388, name=Bikash, dept=Civil, salary=900000]=80
    }
}

Summary

In this post, we have learned about how to sort Maps using Java 8 Streams API.

Thank you for reading. If you found this article helpful, react and share. Cheers.