java - 如何很好地相交从两张 map 构建的两组?

标签 java dictionary java-8 set java-stream

我们的对象有“属性”;他们的当前状态表示为 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/

相关文章:

java - 单元测试 "glue"代码或没有任何真正逻辑的代码

java - 在spring boot中 Autowiring 一个bean,它在主java包中为空,但在测试包中可以工作

python - 根据值索引和字母顺序对python字典进行排序

Java 8 Filter 集基于另一集

datetime - ZonedDateTime 中的 XMLGregorianCalendar 格式日期

java - 构建 jar 后无法运行 exe

java - 如何封装来自处理程序的异常?

python - 这段Python代码中需要 'or default'做什么?

c# - 防止在字典中重复查找相同元素

Java 8、TSL v1 和 javax.net.ssl.SSLHandshakeException : Received fatal alert: handshake_failure