Wednesday, 9 May 2018


Java Stream Example: Filtering Collection by using Stream

package streamconcept;

public class Student {
           
            int sid;
            String sname;
            float marks;
            public Student(int sid, String sname, float marks) {
                        super();
                        this.sid = sid;
                        this.sname = sname;
                        this.marks = marks;
            }
           

}


package streamconcept;

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

public class StudentData {
               
                public List<Student> getData()
                {
                                List<Student> l=new ArrayList<>();
                                Student s1=new Student(101, "govind", 455.00f);
                                Student s2=new Student(102, "rishabh", 435.00f);
                                Student s3=new Student(103, "murari", 460.00f);
                              Student s4=new Student(101, "murlidhar", 433.00f);
                                Student s5=new Student(101, "satyam", 470.00f);
                                l.add(s1);
                                l.add(s2);
                                l.add(s3);
                                l.add(s4);
                                l.add(s5);
                               
                                return l;
                               
                               
                }}

package streamconcept;
import java.util.List;
import java.util.stream.Collectors;

public class StudenClient {
           
            public static void main(String[] args) {
                        StudentData sd=new StudentData();
                        List<Student> ss = sd.getData();
                        List<Float> marks=ss.stream()
                                                .filter(s->s.marks>450)//filtering data
                                                .map(m->m.marks)//fetching data
                                                .collect(Collectors.toList());//collecting as list
                                System.out.println(marks);
                       
            }

}


o/p:------------------------

[455.0, 460.0, 470.0]


No comments:

Post a Comment