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());