[英]How to filter Map by a List using Java 8 stream?
I want to change the following code to use Stream
s, but I didn't find a similar example. 我想将以下代码更改为使用
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));
}
}
I think it could be like this: 我认为可能是这样的:
List<DspInfoEntity> dspInfoList = dspInfoEntityMap.entrySet().stream().filter(?).collect(Collectors.toList());
Your loop filters the appLaunchMappingDtoList
list, so you should stream over the List, not the Map: 您的循环会过滤
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>
or (if your Map
may contain null values and you don't want to filter them out): 或(如果您的
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.