Java 8 - Lambda Expression for Collections:

Lambda Expression for Collections:

  • Using Lambda expression we can sort the collections datas.

ArrayList<Integer> l = new ArrayList<>();
l.add(10);
l.add(20);
l.add(5);
l.add(7);
l.add(25);

Java 7:
Class MyCompartor implements comparator<Interger>{
public int compare(Interger I1, Integer I2){
return (I1 > I2)?-1: (I1 < I2)?1:0);
}
}
Collections.sort(l, new MyComparator());

Java 8:
Collections.sort(l, (I1, I2 ) -> (I1 > I2)?-1: (I1 < I2)?1:0);

TreeSet<Integer> t = new TreeSet<>(); -> Default Natural Sorting.

TreeSet<Integer> t = new TreeSet<>( (I1, I2) -> (I1 > I2)?-1:(I1 < I2)?1:0 );

Below is the example to sort the custom class ,

Class Employee {
private int id;
private String name;

Employee(int id, String name){
this.id = id;
this.name =name;
}
}
Java 8 :

Class Test{
public static void main(String args[]){
ArrayList<Employee> l = new ArrayList<>();
l.add(new Employee(100,"Karthick"));
l.add(new Employee(150,"Suresh"));
l.add(new Employee(110,"Rajesh"));
Collections.sort(l, (e1, e2) -> (e1 < e2)?-1: (e1 > e2)?1:0);
}
}

Comments

Popular posts from this blog

How to set Java Object into JaxBElement ?

GitLab