Di Zou
Di Zou

Reputation: 4619

When using Collectors.toMap in Java, how would I skip adding an entry to the new map?

So here's my code:

HashMap<String, List<Foo.Builder>> strFooMap = new HashMap<>();
// add stuff to strFooMap and do other things
return new HashMap<>(strFooMap.entrySet()
    .stream()
    .collect(Collectors.toMap(Entry::getKey,
        entry -> entry
            .getValue()
            .stream()
            .filter(builder -> {
              // do some conditional stuff to filter
            })
            .map(builder -> {
              return builder.build();
            })
            .collect(Collectors.toList())
        )
    )
);

So sometimes, after doing the filter, all the items in my List<Foo.Builder> will be filtered out. Then in my final HashMap, I have an entry like this: {"someStr" -> []}. I would like to remove the key value pairs where the value is an empty list. How would I go about doing this? Would it be possible to do this while in the .stream().collect(Collectors.toMap(...)) code? Thanks!

Upvotes: 4

Views: 3821

Answers (1)

Nazarii Bardiuk
Nazarii Bardiuk

Reputation: 4342

One of solutions would be to move value transformation before collecting results to map. It gives you possibility to filter out empty values

 List<Foo> transformValue(List<Foo.Builder> value) {
     //original value transformation logic
 }

 <K,V> Entry<K,V> pair(K key, V value){ 
    return new AbstractMap.SimpleEntry<>(key, value);
 }

 strFooMap.entrySet().stream()
      .map(entry -> pair(entry.getKey(), transformValue(entry.getValue()))
      .filter(entry -> !entry.getValue().isEmpty())
      .collect(toMap(Entry::getKey, Entry::getValue));

Upvotes: 5

Related Questions