[英]How to filter Map by a List using Java 8 stream?
我想将以下代码更改为使用Stream
,但是没有找到类似的示例。
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
列表,因此您应流appLaunchMappingDtoList
列表,而不是Map:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.