记录stream处理数据。
筛选某个字段,进行排序展示给前端
//情况1:查询出来的结果是集合,只需要某个字段,进行排序展示给前端。
List<Student> list = new ArrayList<>();
list.add(new Student("第一季度",13));
list.add(new Student("第二季度",11));
list.add(new Student("第三季度",14));
list.add(new Student("第四季度",10));
//升序排序
List<Integer> collect1 = list.stream()
.sorted(Comparator.comparing(Student::getValue))
.map(y -> y.getValue())
.collect(Collectors.toList());
//降序排序
List<Integer> collect = list.stream()
.sorted(Comparator.comparing(Student::getValue).reversed())
.map(y -> y.getValue())
.collect(Collectors.toList());
collect.forEach(x->{
System.out.println(x);
});
集合do对象转实体,批量存数据库。
//情况2:集合do对象转实体,批量存数据库。
List<StudentDO> doList = new ArrayList<>();
doList.add(new StudentDO("小明",12));
doList.add(new StudentDO("小红",11));
//处理对list集合进行复制。
List<Student> collect = doList.stream().map(x -> {
Student student = new Student();
BeanUtils.copyProperties(x, student);
return student;
}).collect(Collectors.toList());
collect.forEach(x->{
System.out.println(x);
});
筛选非空的值。
//情况3:筛选掉用户为null的值。
List<DataEntity> list = new ArrayList<>();
list.add(new DataEntity("测试",1));
list.add(new DataEntity(null,1));
List<DataEntity> collect = list.stream().filter(x -> !Objects.isNull(x.getName())).collect(Collectors.toList());
collect.forEach(x->{
System.out.println(x);
});
根据单个属性去重
List<User> collect1 = listAll.stream()
.collect(Collectors.toMap(User::getName, vehicle -> vehicle, (u1, u2) -> u1))
.values()
.stream()
.collect(Collectors.toList());
根据多个属性去重
根据房间id和居民id去重,只展示一个数据。
List<HouseRentVo> collect = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(
myObject -> Arrays.asList(myObject.getRoomId(), myObject.getResidentId()),
Function.identity(),
(oldValue, newValue) -> oldValue
),
map -> new ArrayList<>(map.values())
));
根据相同属性,叠加值
数据筛选之前
WkPatrolAllShowVo(name=测试克拉拉, dailyInspectionNumber=0, planTasksNumber=2, tempTasksNumber=0)
WkPatrolAllShowVo(name=若依管理员, dailyInspectionNumber=0, planTasksNumber=0, tempTasksNumber=1)
WkPatrolAllShowVo(name=若依管理员, dailyInspectionNumber=0, planTasksNumber=1, tempTasksNumber=0)
筛选之后
WkPatrolAllShowVo(name=测试克拉拉, dailyInspectionNumber=0, planTasksNumber=2, tempTasksNumber=0)
WkPatrolAllShowVo(name=若依管理员, dailyInspectionNumber=0, planTasksNumber=1, tempTasksNumber=1)
List<WkPatrolAllShowVo> collect = list.stream().collect(Collectors.toMap(WkPatrolAllShowVo::getName, a -> a, (o1, o2) -> {
o1.setDailyInspectionNumber(o1.getDailyInspectionNumber() + o2.getDailyInspectionNumber());
o1.setPlanTasksNumber(o1.getPlanTasksNumber() + o2.getPlanTasksNumber());
o1.setTempTasksNumber(o1.getTempTasksNumber() + o2.getTempTasksNumber());
return o1;
})).values().stream().collect(Collectors.toList());
2626

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



