有两张表 一个是学生 一个是学生信息表(按照规范命名的可以直接看字段意思就行)
业务场景: 两个list之间有逻辑外键,进行一个数据的匹配
根据学生id 进行学生和学生信息的匹配(map)
List<Student> collect = students.stream().map(g -> { //学生表进行流化 用map处理 代表单个学生数据的是g
//给g赋值需要 学生信息的一个遍历匹配 根据学生id进行匹配 学生信息表进行流化代表单个数据的是g2
studentInfo.stream().filter(
//进行id和id的匹配 然后遍历赋值
g2 -> Objects.equals(g.getId(), g2.getstudentId())).forEach(
g2 -> {
//给学生表设置 学生的年龄 和性别
g.setStudentAge(g2.getAge());
g.setStudentSex(g2.getSex());
});
return g;
//list集合输出出来
}).collect(Collectors.toList());
业务场景: 过滤学生数据(filter)
//可以一个fifter使用,也可以两个filter过滤连用
List<Student> collect1 = collect.stream().filter(c -> c.getStudentStatus() != null ).filter(c -> c.getStudentStatus().equals(studentInfo.getStudentStatus())).collect(Collectors.toList());
业务场景:算出所有的学生年龄之和(max函数)
//.mapToDouble是给值转换成double类型的 还有.mapToInt 和.mapToLong 意义一样的
//.sum是计算和
double ageSum = student.stream().mapToDouble(stu-> stu.getAge().doubleValue()).sum();
//也可以使用Collectors.summingInt
student.stream.collect(Collectors.summingInt(student::getAge))
业务场景: 提取出学生的生日都有哪些天(过滤)
//大致意思就是 需要输出成集合 输出成集合之前 新建一个TreeSet 根据 学生生日放入集合
//比如张三和李四同一天生日 张三就会被放入到这个集合中 因为Treeset不允许有重复值所以会自动去重
List<Student> birthday = student.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(stu::getBirthday))), ArrayList::new));
业务场景:按学生班级维度分组,并统计每个班有几个人(groupingBy分组)
student.stream.collect(Collectors.groupingBy(student::getClass,
Collectors.counting()))
业务场景:按学生班级维度分组,再按照性别维度分组,并统计每个性别几个人(collect的嵌套使用)
student.stream.collect(Collectors.groupingBy(student::getClass,
Collectors.groupingBy(student::getsex,
Collectors.counting())))
业务场景:选出一班成绩最高的同学(collectingAndThen解决问题)
student.stream.filter(s -> s.getclass.equals("一班")).collect(
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingInt(student::getchengji)),
Optional::get)
)
文章持续更新