Java Stream filter() example
In the following example, we are fetching filtered data as a list.
package govind;
public class Student {
int sid;
String sname;
float smarks;
public Student(int sid, String sname, float smarks) {
super();
this.sid = sid;
this.sname = sname;
this.smarks = smarks;
}
}
package govind;
import
java.util.ArrayList;
import
java.util.List;
import
java.util.stream.Collector;
import
java.util.stream.Collectors;
import
java.util.stream.Stream;
public
class StudentMain {
public
static void
main(String[] args) {
List<Student> l=new
ArrayList<>();
Student s1=new
Student(101, "govind", 455.00f);
Student s2=new
Student(102, "sanjay", 330.00f);
Student s3=new
Student(103, "mani", 395.00f);
Student s4=new
Student(104, "ajit", 460.00f);
Student s5=new
Student(105, "krishna", 490.00f);
l.add(s1);
l.add(s2);
l.add(s3);
l.add(s4);
l.add(s5);
List<Float> markslist = l.stream()
.filter(s->s.smarks>400)//filtering
price
.map(sm->sm.smarks)//fetching
price
.collect(Collectors.toList());
System.out.println(markslist);
}
}
o/p:----------------------------------
[455.0,
460.0, 490.0]
No comments:
Post a Comment