by @kodeazy

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

Home » java » How to sort a list of Objects using streams in Asc order in java?
  • In this blog we will be discussing on how to sort list of objects in java using streams in Asc 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 Objects using streams.

    List<Empoyee> al=new ArrayList<Empoyee>();
    al=al.stream().sorted(Comparator.comparingInt(Empoyee::getAge)).collect(Collectors.toList());
  • Below is an example code how to sort the ArrayList objects using streams in Asc 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)).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 int getAge(){
        return this.age;
    }   
    }

    Output:

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