Java 8 种语法来迭代并调用基于所有元素的否定谓词的方法?

Java 8 syntax to iterate over and call a method based on negated predicate for all elements?

这是我在 Java 7 中所做的:

public class Sample {

    private List<String> list = Lists.newArrayList("helloworld", "foobar", "newyork");

    public void performOperation(String input) {

        boolean found = false;

        for (String each : list) {
            if (input.contains(each)) {
                found = true;
            }
        }

        if (!found) {
            magicMethod(input);
        }
    }

    public void magicMethod(String input) {
        // do the real magic here
    }
}

我希望沿着这条线走下去(由于显而易见的原因,这是错误的)

list.forEach(each -> input.contains(each) ? magicMethod(input) : return );

这是一种方法:

public void performOperation(String input) {
    list.stream().filter(each -> input.contains(each))
        .forEach(s -> this.magicMethod(input));
}

注意:问题已被编辑,所以现在的解决方案完全不同。最好的方法是 中的方法。 这是一个等效的解决方案:

(编辑: 最初,我发布了以下答案,这被认为是 反模式!)

public void performOperation(String input) {
    if (!this.list.stream().filter(each -> 
            input.contains(each)).findAny().isPresent()) {
        this.magicMethod(input);
    }
}

请不要这样做!!!

根据@Holger 的评论,我想强调这是一种反模式这一事实。不要使用 stream.filter(…).findAny().isPresent(),只需使用 anyMatch(...)

对于这个特定的问题,不要使用 !stream.filter(…).findAny().isPresent(),只需使用 noneMatch(...),这是 .

中显示的方法

使用 anyMatchnoneMatch,以在您的特定情况下更清楚的为准:

if (list.stream().noneMatch(input::contains)) {
   magicMethod(input);
}