当前位置: 代码迷 >> 综合 >> java8 stream 的 使用总结(待完善)
  详细解决方案

java8 stream 的 使用总结(待完善)

热度:57   发布时间:2023-12-27 13:48:46.0

在开发中,当使用sql无法快速的查询到想要的结果,或者在查询的结果中在做一次处理,使用stream能优化复杂的查询,这里总结我在开发中使用较多的几种方法

一、提取集合中的字段

List<String> userIds = userList.getData().stream().map(UserInfo::getUserId).collect(Collectors.toList());

二、将集合转化成Map<String, String>

Map<String, String> userMap = subordinateStaff.getData().stream().collect(Collectors.toMap(UserInfoBo::getUserId, UserInfoBo::getUserName));

 将集合转化成Map<String, String>, 当value存在null, 和key存在重复的处理方法

 Map<String, String> map = list.stream().filter(e -> Objects.nonNull(e.getDefaultValue())).collect(Collectors.toMap(StepParamsVo::getParamKey, StepParamsVo::getDefaultValue, (k1, k2) -> k1));

 

三、将集合转化成Map<String, Object>

Map<String, StoreInfo> storeNameMap = storeInfos.stream().collect(Collectors.toMap(StoreInfo::getStoreId, storeInfo -> storeInfo));

 四、将集合转换成 Map<String, List<Object>>

Map<String, List<Object>> collect = parkingImgs.stream().collect(Collectors.toMap(Object::getId,e -> new ArrayList<>(Arrays.asList(e)),(List<Object> oldList, List<Object> newList) -> {oldList.addAll(newList);return oldList;}));
  相关解决方案