简体   繁体   中英

java 8 stream API filter out empty value from map

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

You need to collect into a new Map (say)

eg

 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.

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

Try inserting the filter in-line:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM