java - 如何使用 Java 8 流按列表过滤 Map?
问题描述
我想把下面的代码改成使用Stream
s,但是没有找到类似的例子。
Map<Integer, DspInfoEntity> dspInfoEntityMap = dspInfoService.getDspInfoEntityMap();
List<DspInfoEntity> dspInfoList = new ArrayList<>();
for (AppLaunchMappingDto appLaunchMappingDto : appLaunchMappingDtoList) {
int dspId = appLaunchMappingDto.getDspId();
if (dspInfoEntityMap.containsKey(dspId)) {
dspInfoList.add(dspInfoEntityMap.get(dspId));
}
}
我认为可能是这样的:
List<DspInfoEntity> dspInfoList = dspInfoEntityMap.entrySet().stream().filter(?).collect(Collectors.toList());
解决方案
您的循环过滤appLaunchMappingDtoList
列表,因此您应该流过列表,而不是地图:
List<DspInfoEntity> dspInfoList =
appLaunchMappingDtoList.stream() // Stream<AppLaunchMappingDto>
.map(AppLaunchMappingDto::getDspId) // Stream<Integer>
.map(dspInfoEntityMap::get) // Stream<DspInfoEntity>
.filter(Objects::nonNull)
.collect(Collectors.toList()); // List<DspInfoEntity>
或(如果您Map
可能包含空值并且您不想将它们过滤掉):
List<DspInfoEntity> dspInfoList =
appLaunchMappingDtoList.stream() // Stream<AppLaunchMappingDto>
.map(AppLaunchMappingDto::getDspId) // Stream<Integer>
.filter(dspInfoEntityMap::containsKey)
.map(dspInfoEntityMap::get) // Stream<DspInfoEntity>
.collect(Collectors.toList()); // List<DspInfoEntity>
推荐阅读
- rx-java - 如果 RxJava 失败,如何恢复映射列表
- regex - 具有前瞻模式的 grep 命令不选择任何内容
- html - 文本换行时元素占用 100% 的宽度(flexbox)
- xml - 旧版本产品如何提供方案?
- ruby-on-rails - 如何获得关键字搜索 ransack rails 的最接近匹配
- outlook-addin - 我可以为要使用发送按钮创建的会议设置扩展属性吗?
- regex - 如何从正则表达式模式中只拒绝一个字符串
- perl - 什么是“融合”不同指针指向的位置的好方法?
- android - Android Studio 3.1.3,设计视图总是空的
- windows - Win32 - 确定内存映射文件的脏页