问题
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;
- how can i remove entries with empty/null value from the map?
- 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:
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));
回答2:
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.
回答3:
Try inserting the filter in-line:
userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty())
.forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));
来源:https://stackoverflow.com/questions/47355185/java-8-stream-api-filter-out-empty-value-from-map