by @kodeazy

How to sort a list of Objects in desc order using streams in java?

Home » java » How to sort a list of Objects in desc order using streams in java?
  • In this blog we will be discussing on how to sort list of objects in java using streams in Desc order.
  • To sort the list using streams we sort the list using Comparator function and we collect it as a list using collect function.
  • Below is an example syntax of sorting EmployeeObjects in Desc order using streams.

    List<Empoyee> al=new ArrayList<Empoyee>();
           al=al.stream().sorted(Comparator.comparingInt(Empoyee::getAge).reversed()).collect(Collectors.toList());
  • Below is an example code how to sort the ArrayList objects using streams in Desc order.

    import java.util.*;
    import java.util.stream.Collectors;
    class SortObjectsUsingStream{
    public static void main(String args[]){
        List<Empoyee> al=new ArrayList<Empoyee>();
        al.add(new Empoyee(27, 103, "Suresh"));
        al.add(new Empoyee(23, 102, "Ramesh"));
        al.add(new Empoyee(21, 105, "Mahesh"));
        al.add(new Empoyee(29, 104, "Gopi"));
        System.out.println("Sorting by Age");
            al=al.stream().sorted(Comparator.comparingInt(Empoyee::getAge).reversed()).collect(Collectors.toList());
    
        al.forEach(emplyeDetails->{
            System.out.println("Name is: "+emplyeDetails.name+" Age is :"+emplyeDetails.age+"Salary is "+emplyeDetails.salary);
        });
        
    }
    }
    class Empoyee{
    int age;
    int salary;
    String name;
    Empoyee(int age,int salary,String name){
        this.age=age;
        this.salary=salary;
        this.name=name;
    }
    public String getName(){
        return this.name;
    }
    public int getAge(){
        return this.age;
    }   
    }

    Output:

    D:\java>javac SortObjectsUsingStream.java
    D:\java>java SortObjectsUsingStream
    Sorting by Age
    Name is: Gopi Age is :29 Salary is 104
    Name is: Suresh Age is :27 Salary is 103
    Name is: Ramesh Age is :23 Salary is 102
    Name is: Mahesh Age is :21 Salary is 105