1

i have a map, need to operate on each entry's value, and return the modified map. I managed to get it working, but the resulted map contains entries with empty value, and I want to remove those entries but cannot with Java 8 stream API.

here is my original code:

Map<String, List<Test>> filtered = Maps.newHashMap();
for (String userId : userTests.keySet()) {
    List<Test> tests = userTests.get(userId);
    List<Test> filteredTests = filterByType(tests, supportedTypes);

    if (!CollectionUtils.isEmpty(filteredTests)) {
        filtered.put(userId, filteredTests);
    }
}
return filtered;

and here is my Java 8 stream API version:

userTests.entrySet().stream()
         .forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));

userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty());
        return userTests;
  1. how can i remove entries with empty/null value from the map?
  2. is there better way to write the code in stream API, so far I don't see it's better than my original code
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
user468587
  • 4,799
  • 24
  • 67
  • 124

3 Answers3

3

You need to collect into a new Map (say)

e.g.

 new HashMap<String, List<String>>().
                entrySet().
                stream().
                filter(entry -> !entry.getValue().isEmpty()).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

As it currently stands you're simply returning a stream with the intermediate (filtering) operations. The terminal operation will execute this and give you the desired collection.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
2

userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty()); this has no effect. filter is not a terminal operation.

You need to collect the stream result into a new map:

HashMap<String, String> map = new HashMap<>();
map.put("s","");
map.put("not empty", "not empty");

Map<String, String> notEmtpy = map.entrySet().stream()
     .filter(e -> !e.getValue().isEmpty())
     .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
0

Try inserting the filter in-line:

userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty())
.forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));
Zach
  • 11
  • 2