Friday, 15 June 2018

Sort using lambda exp.


 By using lambda expression we can sort object list using single line of code.

package lambda;

import java.util.ArrayList;
import java.util.List;

public class CompareByName {
    public static void main(String args[]) {
        List<Employee> list = new ArrayList<>();
        list.add(new Employee("sushil",15));
        list.add(new Employee("mittal",25));
        list.add(new Employee("kumar",20));
       
        System.out.println("***********original list*****");
        list.forEach(e-> System.out.println(e));
        System.out.println("***********sort by name******");
        list.sort((e1,e2)-> e1.getName().compareTo(e2.getName()));
        list.forEach(e-> System.out.println(e));
        System.out.println("***********sort by age******");
        list.sort((e1,e2)-> e1.getAge()- e2.getAge());
        list.forEach(e-> System.out.println(e));
    }
   
     static class Employee{
        String name;
        Integer age;
       
        public Employee(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

       
        public String getName() {
            return name;
        }

       
        public void setName(String name) {
            this.name = name;
        }

       
        public Integer getAge() {
            return age;
        }

       
        public void setAge(Integer age) {
            this.age = age;
        }


        @Override
        public String toString() {
            return "Employee [name=" + name + ", age=" + age + "]";
        }
       
    }
   
}


output:
 ***********original list*****
Employee [name=sushil, age=15]
Employee [name=mittal, age=25]
Employee [name=kumar, age=20]
***********sort by name******
Employee [name=kumar, age=20]
Employee [name=mittal, age=25]
Employee [name=sushil, age=15]
***********sort by age******
Employee [name=sushil, age=15]
Employee [name=kumar, age=20]
Employee [name=mittal, age=25]



No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...