1、基本概念
filter方法是Stream API中的一个中间操作,filter方法 以 谓词(Predicate)作为参数,该谓词主要判断集合中的元素是否满足条件,只有返回true的元素才会被保留到结果流中。
2、实际Demo
2.1 实体类
public class Student {
//姓名
private String name;
//年龄
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.2 filter方法的实际运用
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args) {
List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Predicate<Integer> predicate = n -> n > 5;
//collect方法,可以将结果流中的元素收集到一个新的集合,或者其他数据结构当中去
List<Integer> newNumList = numList.stream().filter(predicate).collect(Collectors.toList());
System.out.println("过滤掉小于5的数据之后,新集合元素为:" + newNumList);
List<Student> stuList = new ArrayList<>();
stuList.add(new Student("王五", 26));
stuList.add(new Student("张三", 18));
stuList.add(new Student("赵六", 30));
stuList.add(new Student("李四", 20));
stuList.add(new Student("黑神话.悟空", 100));
stuList.add(new Student("纳西妲", 5));
//使用两个谓词,收集年龄大于25,或者名字是"纳西妲"的元素
List<Student> result =
stuList.stream()
.filter(buildPredicate()
.or(stu -> stu.getName().equals("纳西妲"))
).collect(Collectors.toList());
System.out.println("收集年龄大于25,或者名字是纳西妲的元素:"+result);
}
/**
* 构建一个谓词(Predicate),过滤小于25岁的集合元素
*
*/
private static Predicate<Student> buildPredicate() {
Predicate<Student> predicate = stu -> {
if (stu.getAge() > 25) {
//true表示元素会被保留在结果流中
return true;
} else {
//false表示元素会被过滤出去
return false;
}
};
return predicate;
}
}
2.3 输出结果
过滤掉小于5的数据之后,新集合元素为:[6, 7, 8, 9, 10]
收集年龄大于25,或者名字是纳西妲的元素:[Student{name='王五', age=26}, Student{name='赵六', age=30}, Student{name='黑神话.悟空', age=100}, Student{name='纳西妲', age=5}]