1

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

Anthony
  • 189
  • 1
  • 15

1 Answers1

0

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(); 
Naman
  • 27,789
  • 26
  • 218
  • 353