【发布时间】:2018-02-09 04:02:38
【问题描述】:
这是类项目。
public class Item {
String id;
String name;
Integer value;
Boolean status;
}
我有一个地图(字符串,集合(项目))。我想编写一个返回 Map(String, Set(Item)) 的方法,使得结果映射中只存在 status = false 或 status = null 的 Items。我不想要一个集合范围的操作。我希望生成的子集仅包含那些状态 == Boolean.FALSE 或状态 == null 的项目。我不希望整个集合被包含或排除。我只希望根据状态值包含或排除那些单独的项目。
这是我迄今为止尝试过的。
public Map<String,Set<Item>> filterByStatus(Map<String, Set<Item>> changes) {
return changes.entrySet()
.stream()
.filter(p -> p.getValue()
.stream()
.anyMatch(item -> BooleanUtils.isNotTrue(item.isStatus())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
没用!如果我不调用 filterByStatus,我会得到相同的结果。
更新
public Map<String,Set<Item>> filterByStatus(Map<String, Set<Item>> changes) {
return changes.entrySet()
.stream()
.map(p -> p.getValue()
.stream()
.filter(item -> BooleanUtils.isNotTrue(item.isStatus())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
结果:collect(Collectors.toMap()) 行中出现错误,指出无法从静态上下文引用非静态方法。
【问题讨论】:
-
在您的代码中,
p是Set<Item>。anyMatch()表示如果整个集合中有任何一个为假,则整个集合都会被包含在内。 -
哦,我根本不想要那个。所以,我想要的是在 Set 中有任何那些具有 status == Boolean.FALSE 或 status == null 的项目。我不希望整个集合被包含或排除。我只希望根据状态值包含或排除那些单独的项目。状态是一个布尔值。让我更新问题以包含这些详细信息。
-
谢谢赛拉斯。从p中,如何在保留Set的同时根据条件过滤掉所有Item?我会用我尝试做的事情来更新问题。
标签: java java-8 hashmap java-stream