如何使用Java 8流按列表过​​滤地图?

时间:2019-02-18 07:06:42

标签: java lambda java-8

我想将以下代码更改为使用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());

1 个答案:

答案 0 :(得分:3)

您的循环会过滤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>
相关问题