How to filter Map by a List using Java 8 stream?

Wilbur :

I want to change the following code to use Streams, but I didn't find a similar example.

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

Your loop filters the appLaunchMappingDtoList list, so you should stream over the List, not the 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):

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>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147755&siteId=1