简体   繁体   中英

Java 8 filter based on a boolean

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

对我来说听起来很简单或有条件。

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

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

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

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

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());
}

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

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());

You can use the anyMatch method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM