Friday 9 December 2016

Java 8 - Lambda Expression sample - Filter and Sort


Scenario :
===========

If we want to dispaly Student details with age > 30 and sort by StudentName and get the result students in List.



import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class Java8 {
    public static void main(String[] args) {
        Student std1 = new Student();
        Student std2 = new Student();
        Student std3 = new Student();
        Student std4 = new Student();

        std1.setStudId(1); std1.setStudName("xxx"); std1.setAge(44);
        std2.setStudId(22); std2.setStudName("zzz"); std2.setAge(22);
        std3.setStudId(3); std3.setStudName("fff"); std3.setAge(32);
        std4.setStudId(44); std4.setStudName("mmm"); std4.setAge(66);

        List<Student> studentList = new ArrayList<Student>();
        studentList.add(std1);studentList.add(std2);studentList.add(std3);studentList.add(std4);

        List<Student> list = studentList.stream()
                                .filter(st -> st.getAge() > 30)
                                .sorted(Comparator.comparing(Student::getStudName))
                                .collect(toList());

        list.forEach(System.out::println);
    }
}

class Student{

    @Override    public int hashCode() {
        return new Integer(31*studId).hashCode();
    }

    @Override    public boolean equals(Object obj) {
        return super.equals(obj);
    }

    @Override    public String toString() {
        return "Student{" +
                "studId=" + studId +
                ", studName='" + studName + '\'' +
                ", Age=" + Age +
                '}';
    }

    int studId;
    String studName;
    int Age;

    public int getStudId() {
        return studId;
    }

    public void setStudId(int studId) {
        this.studId = studId;
    }

    public String getStudName() {
        return studName;
    }

    public void setStudName(String studName) {
        this.studName = studName;
    }

    public int getAge() {
        return Age;
    }

    public void setAge(int age) {
        Age = age;
    }
}

Output:
-----------

Student{studId=3, studName='fff', Age=32}
Student{studId=44, studName='mmm', Age=66}
Student{studId=1, studName='xxx', Age=44}

No comments:

Post a Comment