Merge a List of pojos into a Map of integers that can be combined on a key

56 views Asked by At

I am trying to stream-ify the following logic:

I have a map of Integer ids to an integer count. I have a list of Pojos that represent the ids. I want to merge the two and have a map of pojos to integer count.

Currently I have:

  return EntryStream.of(idToCountMapping)
      .mapKeys(k -> StreamEx.of(pojos).findFirst(s -> s.getId().equals(k)))
      .filterKeys(Optional::isPresent)
      .mapKeys(Optional::get)
      .mapKeyValue(SuperCoolNewPojo::new)
      .toList(); 

The first mapKeys() call strikes me as something that is probably much better expressed in a different way.

Any help would be great!

Thanks, Anthony

1

There are 1 answers

0
Naman On

Though I wouldn't be able to answer to the completeness based on streamex, yet from what I can infer and conceptualize as an approach using streams :

The collection pojos can be transformed into a Map such as:

Map<String, POJO> idToPojoMap = pojos.stream()
                                     .collect(Collectors.toMap(Pojo::getId, 
                                                   Function.identity(), (a,b) -> a);

further, its use in your code becomes simpler as:

return EntryStream.of(idToCountMapping)
      .filterKeys(k -> idToPojoMap.keySet().contains(k)) // only if part of the created map
      .mapKeyValue(SuperCoolNewPojo::new)
      .toList();