2

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());
3
  • 2
    Your imperative code filters a list: appLaunchMappingDtoList. That's also what the functional code should do. Commented Feb 18, 2019 at 7:11
  • You're iterate over a List not over a Map in dspInfoEntityMap.entrySet() or I'm wrong with that? Commented Feb 18, 2019 at 7:13
  • Perhapsfilter(dspInfoEntityMap::containsKey).mapToObj(dspInfoEntityMap::get)? Commented Feb 18, 2019 at 7:15

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.