Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)

2年前 (2022) 程序员胖胖胖虎阿
246 0 0

内容简介

本文主要说明在Java8及以上版本中,使用stream().filter()来过滤一个List对象,查找符合条件的对象集合。

List对象类(StudentInfo)

 StudentInfo对象类

//测试数据,请不要纠结数据的严谨性
List<StudentInfo> studentList = new ArrayList<>();
studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));
studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));

Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)

输出Students列表

 //输出List
StudentInfo.printStudents(studentList);

输出结果如下图:

Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)

 使用filter()过滤List

//查找身高在1.8米及以上的男生
List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());
//输出查找结果
StudentInfo.printStudents(boys);

结果如下图:

Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)

相关文章

暂无评论

暂无评论...