对于java stream流的使用心得

对于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)
  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值