使用 Java 8 谓词查找 "most" 正确值

Finding the "most" correct value using Java 8 Predicate

感谢您查看我的问题!

我在使用以特定顺序应用多个谓词的 Streams 时遇到了一些麻烦。

为了示例,请考虑以下 IntPredicates:

        IntPredicate divisibleByThree = i -> i % 3 == 0;
        IntPredicate divisibleByFour = i -> i % 4 == 0;
        IntPredicate divisibleByFive = i -> i % 5 == 0;
        IntPredicate divisibleByThreeAndFour = divisibleByThree.and(divisibleByFour);
        IntPredicate divisibleByThreeAndFive = divisibleByThree.and(divisibleByFive);
        IntPredicate divisibleByThreeAndFiveAndFour = divisibleByThreeAndFour.and(divisibleByFive);
        //....arbitrary Number of predicates.

第 1 部分

我已将我遇到的问题转换为 "FizzBuzz" 式版本,试图通过以特定顺序将谓词应用于流来找到正确答案。像这样:

    IntStream.range(1, 100).forEach(i -> {
        //Order matters here!
        if(divisibleByThreeAndFiveAndFour.test(i)){
            System.out.println("Three and four and five");
        } else if(divisibleByThreeAndFour.test(i)){
            System.out.println("Three and four");
        } else if(divisibleByThreeAndFive.test(i)){
            System.out.println("Three and four");
        } else if(divisibleByFive.test(i)){
            System.out.println("Five");
        }
        //etc, etc.
    });

我不认为这是非常漂亮的代码,有没有更好的方法来实现它?

第 2 部分

如果我真的需要应用谓词来查看流中是否存在适当的值,并计算要返回的相关值(在本例中为要打印的字符串),那该怎么办?那看起来会怎样?

提议的天真的解决方案:

String bestValueFound = "None found";
if(IntStream.range(1, 100).filter(divisibleByThreeAndFiveAndFour).findFirst().isPresent()){
    bestValueFound = "Three and four and five";
} else if(IntStream.range(1, 100).filter(divisibleByThreeAndFour).findFirst().isPresent()){
    bestValueFound = "Three and four";
}else if(IntStream.range(1, 100).filter(divisibleByThreeAndFive).findFirst().isPresent()){
    bestValueFound = "Three and five";
} else if(IntStream.range(1, 100).filter(divisibleByThreeAndFive).findFirst().isPresent()){
    bestValueFound = "Five";
}
System.out.println(bestValueFound);

这似乎更糟,无论是在美学上还是因为增加了迭代。

第 3 部分

是否可以使用 JavaSlang 匹配以更漂亮、更有效的方式解决这个问题?

//Note: Predicates needed to be changed from IntPredicate to Predicate<Integer> for correct compilation.
Function<Integer, String> findString = i -> API.Match(i).of(
        Case(divisibleByThreeAndFiveAndFour, "Three and four and five"),
        Case(divisibleByThreeAndFour, "Three and four"),
        Case(divisibleByThreeAndFive, "Three and five"),
        Case(divisibleByFive, "Fice"),
        Case($(), "None found"));
String bestValueFound =  IntStream.range(1, 100).boxed().map(findString).findFirst().orElseThrow(() -> new RuntimeException("Something went wrong?"));
System.out.println(bestValueFound);

这里明显的问题是“.findFirst()”,在这种情况下它是整数 1,使整个表达式的计算结果为 "None found",然后终止。

我想要的是基本上获取与我的匹配中第一个谓词匹配的任何内容,并使用该值(如果存在),如果没有找到与第一个匹配的匹配项,则只给我匹配第二个 Case 的任何内容,依此类推,如果流中没有值与任何谓词匹配,则只给我默认值("None found")。

一定有更好的方法,对吧?还是我只是在浪费时间尝试做一些最好留给更传统的命令式风格的事情?

感谢您阅读我的问题!

您可以创建一个class来封装谓词及其名称:

class NamedPredicate {
    final String name;
    final IntPredicate predicate;

    NamedPredicate(String name, IntPredicate predicate) {
        this.name = name;
        this.predicate = predicate;
    }

    NamedPredicate and(NamedPredicate other) {
        return new NamedPredicate(this.name + " and " + other.name,
                this.predicate.and(other.predicate));
    }
}

and() 方法让我们可以像您原来那样组合它们:

NamedPredicate divisibleByThree = new NamedPredicate("three", i -> i % 3 == 0);
NamedPredicate divisibleByFour = new NamedPredicate("four", i -> i % 4 == 0);
NamedPredicate divisibleByFive = new NamedPredicate("five", i -> i % 5 == 0);
NamedPredicate divisibleByThreeAndFour = divisibleByThree.and(divisibleByFour);
NamedPredicate divisibleByThreeAndFive = divisibleByThree.and(divisibleByFive);
NamedPredicate divisibleByThreeAndFiveAndFour = divisibleByThreeAndFour.and(divisibleByFive);

现在我们可以按降序流过它们并打印第一个匹配谓词的名称,对于每个 i:

IntStream.range(1, 100)
        .mapToObj(i -> Stream.of(
                    divisibleByThreeAndFiveAndFour,
                    divisibleByThreeAndFour,
                    divisibleByThreeAndFive,
                    divisibleByFive,
                    divisibleByFour,
                    divisibleByThree)
                .filter(p -> p.predicate.test(i))
                .findFirst()
                .map(p -> p.name)
                .orElse("none"))
        .forEach(System.out::println);