Java 8 Stream API优化Push消息分组
使用Java 8 Stream API优化Push消息分组
原始代码如下:
Map<String, List<Push>> map = new HashMap<>();
pushMapper.getList(map);
List<Push> pushList = map.getOrDefault("result", new ArrayList<>());
return pushList.stream()
.collect(Collectors.groupingBy(Push::getModule))
.entrySet()
.stream()
.map(i -> PushVO.builder()
.module(i.getKey())
.messageList(PushConverter.INSTANCE.toPushDTO(i.getValue()))
.build())
.collect(Collectors.toList());
可以使用Java 8的Stream API优化代码,如下所示:
List<PushVO> result = pushMapper.getList(new HashMap<>()).stream()
.collect(Collectors.groupingBy(Push::getModule))
.entrySet()
.stream()
.map(entry -> PushVO.builder()
.module(entry.getKey())
.messageList(entry.getValue().stream()
.map(PushConverter.INSTANCE::toPushDTO)
.collect(Collectors.toList()))
.build())
.collect(Collectors.toList());
其中,我们使用流(Stream)进行了以下操作:
- 使用
pushMapper.getList(new HashMap<>()).stream()将List转换为Stream。 - 使用
Collectors.groupingBy(Push::getModule)按照模块进行分组。 - 使用
entrySet().stream()将Map.Entry集合转换为Stream。 - 使用
map()将每个Map.Entry转换为PushVO对象。 - 在PushVO对象中,使用
getValue().stream()将List转换为Stream。 - 使用
map()将每个Push转换为对应的DTO对象。 - 使用
Collectors.toList()将DTO对象的Stream转换为List。 - 使用
build()方法构建PushVO对象。 - 使用
Collectors.toList()将PushVO对象的Stream转换为List。
这样,我们就可以优化代码,使其更加简洁、易读。
原文地址: https://www.cveoy.top/t/topic/mVyL 著作权归作者所有。请勿转载和采集!