更新时间:2022-07-18 10:42:28
Stream<Student> stream = list.stream();
stream = stream.filter(p->p.getSex=='男');
package com.fantJ.JAVA_8;
/**
* Created by Fant.J.
* 2017/12/12 21:46
*/
public class Student {
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public Student(String name, String sex, int age) {
this.name = name;
this.age = age;
this.sex = sex;
}
}
package com.fantJ.JAVA_8;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* Created by Fant.J.
* 2017/12/12 21:46
*/
public class Stream_Collection {
public static void main(String[] args) {
List<Student> list = init();
//获取stream对象
Stream<Student> stream = list.stream();
//遍历集合
stream.forEach(p-> System.out.println(p.toString()));
}
static List<Student> init(){
List<Student> list = new ArrayList<>();
Student student = new Student("老焦","男",1);
list.add(student);
student = new Student("老王","男",1);
list.add(student);
student = new Student("老赵","女",1);
list.add(student);
return list;
}
}
稍微修改下Stream_Collection这个类的main方法如下,
List<Student> list = init();
//stream过滤器的实例
list.stream()
.filter(p->p.getSex()
.equals("女"))
.forEach(p-> System.out.println(p.toString()));
这个过滤器是实现对性别是“女”进行过滤并打印。