java 8 stream API从地图中过滤掉空值 [英] java 8 stream API filter out empty value from map
本文介绍了java 8 stream API从地图中过滤掉空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张地图,需要对每个条目的值进行操作,并返回修改后的地图。我设法让它工作,但结果映射包含空值的条目,我想删除这些条目,但不能使用Java 8流API。
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.
这里是我的原始代码:
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;
这是我的Java 8流API版本:
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;
- 如何从地图中删除空/空值的条目?
- 有更好的方法在流API中编写代码,到目前为止我看不到它比我的原始代码更好
推荐答案
userTests.entrySet()。stream()。filter(entry - >!entry.getValue()。isEmpty( ));
这没有效果。 过滤器
不是终端操作。
您需要将流结果收集到新地图中:
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));
这篇关于java 8 stream API从地图中过滤掉空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文