【问题标题】:Composing predicates excercise JAVA hyperskill编写谓词练习 JAVA hyperskill
【发布时间】:2020-05-04 17:34:57
【问题描述】:

我正在 Hyperskill 上练习我的 Java 技能,但我无法弄清楚这个关于组合谓词的练习。

编写接受 IntPredicate 列表并返回单个 IntPredicate 的 disjunctAll 方法。结果谓词是所有输入谓词的析取。

如果输入列表为空,则结果谓词应为任何整数值返回 false(始终为 false)。

重要。注意提供的方法模板。不要改变它。

public static IntPredicate disjunctAll(List<IntPredicate> predicates) {

}

【问题讨论】:

  • 提示:流减少?

标签: java predicate


【解决方案1】:

列表的简单迭代就可以做到:

    public static IntPredicate disjunctAll(List<IntPredicate> predicates)
    {
        IntPredicate result = i -> false;
        for (IntPredicate p: predicates) {
            result = p.or(result);
        }
        return result;
    }

或者简单地使用流缩减器:

    public static IntPredicate disjunctAll(List<IntPredicate> predicates)
    {
        return predicates.stream()
            .reduce(i -> false, IntPredicate::or);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 2021-10-21
    相关资源
    最近更新 更多