对于java stream流的使用心得
sorted 排序
多条件排序:
dayPlans = dayPlans.stream()
.sorted(Comparator.comparing(DayPlan::getWorkDate)
.thenComparing(DayPlan::getShiftCode)
.thenComparing(DayPlan::getSeqNo))
.collect(Collectors.toList());
单条件排序:
dayPlans = dayPlans.stream()
.sorted(Comparator.comparing(DayPlan::getWorkDate))
.collect(Collectors.toList());
reversed
可以使用.reversed()对查找的结果进行反序,在Comparator.comparing()末尾添加即可
dayPlans = dayPlans.stream()
.sorted(Comparator.comparing(DayPlan::getWorkDate)
.thenComparing(DayPlan::getShiftCode)
.thenComparing(DayPlan::getSeqNo).reversed()
)
.collect(Collectors.toList());
map:以某一字段筛选出一个新的集合
distinct:去重
map,distinct以字段筛选且去重
dayPlans.stream().map(DayPlan::getgetWorkDate).distinct().collect(Collectors.toList())
collect(Collectors.toList()) 生成一个集合
collect(Collectors.toList())
Collectors.groupingBy 分组
可以进行多种分组操作:
当前使用的是List<DayPlan> dayPlans
多属性分组:
Map<List<Object>, List<DayPlan>> dayPlansByKeyValue = dayPlans.stream()
.collect(Collectors.groupingBy(
x -> Arrays.asList(x.getVisitGkey(), x.getWorkSummary())
));
多属性字符串分组:
Map<String, List<DayPlan>> groupedDayPlans = dayPlans.stream()
.collect(Collectors.groupingBy(
dayPlan -> dayPlan.getVisitGkey() + ":" + dayPlan.getWorkSummary()
));
单属性分组:
Map<String, List<DayPlan>> groupedDayPlans = dayPlans.stream()
.collect(Collectors.groupingBy(
dayPlan -> dayPlan.getVisitGkey()
));
值得注意的是,在Collectors.groupingBy里,其实有第二个参数,即前面是条件的项,后面是分出来的列表项(不写会默认使用Collectors.toList())
多属性字符串分组:
Map<String, List<DayPlan>> groupedDayPlans = dayPlans.stream()
.collect(Collectors.groupingBy(
dayPlan -> dayPlan.getVisitGkey() + ":" + dayPlan.getWorkSummary(),
Collectors.toList()));
collect(Collectors.toMap(字段1,字段2))
生成一个包含对象两个字段的map
.collect(Collectors.toMap(DayPlan::getClientRoleToken, DayPlan::getGkey));
findFirst
获得集合中第一个元素
Optional<LocalDateTime> first = dayPlans.stream().map(DayPlan::getAlterTime).findFirst();
在使用后我们看到,返回的是一个Optional类型,如果为了取值,我们可以使用get()
LocalDateTime first = dayPlans.stream().map(DayPlan::getAlterTime).findFirst().get();
但是这在java里可能有一些需要判断是否为空的风险,
因此,我推荐直接使用orElse()
LocalDateTime first = dayPlans.stream().map(DayPlan::getAlterTime).findFirst().orElse(null);
你可以在其为空时,给其赋一个空值,或是一个你希望的其他值,使用起来更优雅一点
anyMatch
判断是否有属性满足条件
boolean isExist = dayPlans.stream().anyMatch(x -> x.getTallyDate() == null)