基于布尔值的 Java 8 过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45314571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:38:06  来源:igfitidea点击:

Java 8 filter based on a boolean

javajava-8

提问by Nick01

I want to be able to apply a filter based on the boolean passed in.

我希望能够根据传入的布尔值应用过滤器。

public static List<Integer> multiplyNumbers(List<Integer> input, boolean ignoreEven){

    return input.stream()
    .filter(number -> !(number%2==0))
    .map(number -> number*2)
    .collect(Collectors.toList());
}

I want to make the filter step based on the ignoreEven flag. If its true, ignore even numbers. How do I go about doing it? I am doing this to avoid code duplication

我想根据 ignoreEven 标志进行过滤步骤。如果为真,则忽略偶数。我该怎么做?我这样做是为了避免代码重复

采纳答案by Joe C

Sounds like a straightforward or condition to me.

对我来说,这听起来像是一个简单的条件。

.filter(number -> !ignoreEven || (number % 2 != 0))

回答by shmosel

If you don't want to check ignoreEvenfor each element, you can define the predicate itself conditionally:

如果不想检查ignoreEven每个元素,可以有条件地定义谓词本身:

.filter(ignoreEven ? (n -> n % 2 != 0) : (n -> true))

回答by Jagannath

You can pass the condition to your multiply(...)method and pass it in filteras shown below.

您可以将条件传递给您的multiply(...)方法并将其传入filter,如下所示。

multiplyNumbers(Arrays.asList(1, 2, 3, 4, 5), (x) -> x % 2 != 0).forEach(System.out::println);

public static List<Integer> multiplyNumbers(List<Integer> input,    
                                            Predicate<Integer> filterCondition){

     return input.stream()
                        .filter(filterCondition)
                        .map(number -> number*2)
                        .collect(Collectors.toList());
}

回答by Grzegorz Piwowarek

You can define two additional helper methods and compose them using or()method:

您可以定义两个额外的辅助方法并使用or()方法组合它们:

private static Predicate<Integer> ignoringEven(boolean ignoreEven) {
    return number -> !ignoreEven;
}

private static Predicate<Integer> ignoringOdd() {
    return number -> (number % 2 != 0);
}

Final result:

最后结果:

return input.stream()
      .filter(ignoringEven(ignoreEven).or(ignoringOdd()))
      .map(number -> number * 2)
      .collect(Collectors.toList());

回答by David Leonardo Bernal

You can use the anyMatch method:

您可以使用 anyMatch 方法:

return swiftTemplateList.stream()
    .map(swiftTemplate -> swiftTemplate.getName())
    .anyMatch(name -> name.equalsIgnoreCase(messageName));