1、filter:筛选
Student stu1 = new Student(1, 19, "张亮");
Student stu2 = new Student(2, 29, "周文");
Student stu3 = new Student(3, 23, "王彪");
List<Student> stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
stuList.add(stu3);
//筛选年龄大于22岁的学生
List<Student> students = stuList
.stream()
.filter(student -> student.getAge() > 22)
.collect(Collectors.toList());
//结果students:[Student(id=2, age=29, name=周文), Student(id=3, age=23, name=王彪)]
2、map:转换
Student stu1 = new Student(1, 19, "张亮");
Student stu2 = new Student(2, 29, "周文");
Student stu3 = new Student(3, 23, "王彪");
List<Student> stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
stuList.add(stu3);
List<String> names = stuList
.stream()
.map(student -> student.getName())
.collect(Collectors.toList());
//结果names:[张亮, 周文, 王彪]
3、distinct:去重
Student stu1 = new Student(1, 19, "张亮");
Student stu2 = new Student(2, 29, "周文");
Student stu3 = new Student(3, 23, "王彪");
Student stu4 = new Student(1, 19, "张亮");
List<Student> stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
stuList.add(stu3);
List<Student> students = stuList
.stream()
.distinct()
.collect(Collectors.toList());
//结果students:[Student(id=1, age=19, name=张亮), Student(id=2, age=29, name=周文), Student(id=3, age=23, name=王彪)]
4、anyMatch:Stream 中任意一个元素符合传入的 predicate,返回 true
Student stu1 = new Student(1, 19, "张亮");
Student stu2 = new Student(2, 29, "周文");
Student stu3 = new Student(3, 23, "王彪");
List<Student> stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
stuList.add(stu3);
boolean anyMatchFlag = stuList
.stream()
.anyMatch(student -> "王彪".equals(student.getName()));
//结果anyMatchFlag:true
Java8中的Stream操作集合
最新推荐文章于 2023-03-22 11:27:16 发布
本文详细介绍了Java Stream API中的四个核心操作:filter用于筛选符合条件的元素;map用于将元素转换为另一种形式;distinct用于去除重复元素;anyMatch用于检查是否至少有一个元素符合指定条件。通过具体示例,展示了如何使用这些操作高效地处理集合数据。
988

被折叠的 条评论
为什么被折叠?



