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操作集合
最新推荐文章于 2022-10-09 17:52:47 发布