首页 > 解决方案 > 如何使用 Java 8 流按列表过​​滤 Map?

问题描述

我想把下面的代码改成使用Streams,但是没有找到类似的例子。

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());

标签: javalambdajava-8

解决方案


您的循环过滤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>

推荐阅读