我们的对象有“属性”;他们的当前状态表示为 Map<String, Object>
其中键类似于属性的名称。这些值可以有不同的类型,不过我当前的任务只是处理 boolean 属性。
除了当前状态之外,对象的“更新”也通过此类 map 进行组织。
现在我必须阻止当前为 true
的属性被禁用(转向 false
)。
使用流,这在这里有效:
Set<String> currentlyEnabled = currentObjectPropertiesMap.
.entrySet()
.stream()
.filter(e -> Boolean.TRUE.equals(e.getValue()))
.map(Entry::getKey)
.collect(Collectors.toSet());
Set<String> goingDisabled = updatedObjectPropertiesMap
.entrySet()
.stream()
.filter(e -> Boolean.FALSE.equals(e.getValue()))
.map(Entry::getKey)
.collect(Collectors.toSet());
currentlyEnabled.retainAll(goingDisabled);
if (currentlyEnabled.isEmpty()) {
return;
} else {
throw new SomeExceptionThatKnowsAllBadProperties(currentlyEnabled);
}
上面的代码首先获取了所有属性的集合 true
, 然后它单独收集所有将变为 false
的属性.如果这两个集合的交集为空,我很好,否则错误。
上面的方法有效,但我觉得它很笨拙,而且我不喜欢 currentlyEnabled
set 被误用于计算交集。
关于如何以更惯用但可读的“流式”方式完成此操作的任何建议?
最佳答案
您可以只选择所有值为 true
的键值对,然后通过键检查“update”-map 中的值是否为 false
.
Set<String> matches = currentObjectPropertiesMap
.entrySet()
.stream()
.filter(e -> Boolean.TRUE.equals(e.getValue()))
.map(Map.Entry::getKey)
.filter(k -> Boolean.FALSE.equals(
updatedObjectPropertiesMap.get(k)
))
.collect(Collectors.toSet());
if(!matches.isEmpty()) throw ...
关于java - 如何很好地相交从两张 map 构建的两组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55571912/