[英]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.
我设法让它工作,但结果映射包含空值的条目,我想删除这些条目,但不能使用Java 8流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: 这是我的Java 8流API版本:
userTests.entrySet().stream()
.forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));
userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty());
return userTests;
You need to collect into a new Map
(say) 你需要收集一张新
Map
(比方说)
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. filter
不是终端操作。
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)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.