Stream.filter()
Stream<T> filter(Predicate<? super T> predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.
filter保留符合predicate的元素
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("张一", 1, 13, "3"));
studentList.add(new Student("张二", 2, 13, "4"));
studentList.add(new Student("张三", 3, 14, "4"));
studentList.add(new Student("老王", 4, 14, "2"));
studentList.add(new Student("张四", 1, 15, "3"));
studentList.add(new Student("张五", 2, 16, "1"));
studentList.add(new Student("张六", 3, 17, "3"));
studentList.add(new Student("张七", 3, 18, "5"));
studentList.add(new Student("老王", 1, 15, "1"));
studentList.add(new Student("张八", 5, 15, "3"));
studentList.add(new Student("张九", 2, 15, "2"));
studentList.add(new Student("老王", 4, 13, "3"));
List<Student> collect = studentList.stream().filter(s -> Objects.nonNull(s.getClassNum()) && "2".equals(s.getClassNum())).collect(Collectors.toList());
collect.forEach(System.out::println);
List<Student> collect1 = studentList.stream().filter(new Predicate<Student>() {
@Override
public boolean test(Student student) {
return Objects.nonNull(student.getClassNum()) && "2".equals(student.getClassNum());
}
}).collect(Collectors.toList());
output
Student{stuName='老王', stuId=4, stuAge=14, classNum='2'}
Student{stuName='张九', stuId=2, stuAge=15, classNum='2'}
filter源码中进行了Objects.requireNonNull(predicate);
判断,为空会抛出空指针异常