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
1
  • Where is the definition of the filterByType method ? Commented Nov 17, 2017 at 16:37

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

0

Try inserting the filter in-line:

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

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.