Java 8 filter based on a boolean

Viewed 33889

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

5 Answers

You can use the anyMatch method:

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