java 8 stream API filter out empty value from map

有些话、适合烂在心里 提交于 2019-12-11 10:40:36

问题


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:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!