lamada表达式的日常使用案例

stream的Collectors.groupingBy()方法的大坑    

不能那为null

Exception in thread “main” 
java.lang.NullPointerException: 
element cannot be mapped to a null key

多条件转换需求

1)将一个list对象基于某个key 按照 key分组

2)然后将每个key对应的value的list的总量进行一个单独的计数统计,

3)计数统计的值count最终还需要把count的值转成String格式

//基于某个值activityId进行分组,然后将分组获取到的数据进行cout(*)计算总量



 List<CommonMessageRecord> records = commonMessageRecordDao.getActivityJoinInfo(list, userUniqueId);


Map<String, String>  count = records.stream().collect(
                            Collectors.groupingBy(
                                    X -> Objects.isNull(X.getActivityId()) ? "0" : X.getActivityId().toString(),
                                    Collectors.collectingAndThen(
                                            Collectors.counting(), e -> e.toString()
                                    )
                            )
                    );

初始化某个结构需求     






 Map<String, Long> totalCount =
 list.stream().collect(Collectors.toMap(Function.identity(), Long -> 0L));

  
 Map<String, String> count = list.stream().collect(Collectors.toMap(Function.identity(), String -> "0"));

基于条件负责需求

// 根据题库进行分组
            Map<Integer, List<QuestionSubmit>> bankSubmitMap = questionSubmits.stream().collect(Collectors.groupingBy(QuestionSubmit::getBankId));



//list<DO>基于某个关键数据optionId转成Map结构,如果出现重复,使用后者代替前者的策略

 Map<String, CommonVoteOption> map = voteOptionIds.stream().collect(Collectors.toMap(CommonVoteOption::getOptionId, Function.identity(), (v1, v2) -> v2));

过滤数据组装成map:

       
//1)list过滤
//2)list转map
List<AccountDomainEnum> accountDomainEnums = Arrays.asList(values);
        // 全部的数据
        Map<Integer, AccountDomainEnum> collect = 
                accountDomainEnums.stream().
                        filter(
                account -> accountDomainList.contains(account.getValue())
        ).collect(
                Collectors.toMap(AccountDomainEnum::getValue, Function.identity())
                );

过滤数据组装:

//数据过滤对应filter
 
List<AccountDomainEnum> accountDomainEnumList =
 accountDomainEnums.stream().filter(
            account -> accountDomainList.contains(account.getValue())
).collect(Collectors.toList());
        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值