Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 filter based on a boolean

Tags:

java

java-8

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

like image 800
Nick01 Avatar asked Jul 25 '17 22:07

Nick01


People also ask

What is Boolean filtering?

The filter(Boolean) step does the following: Passes each item in the array to the Boolean() object. The Boolean() object coerces each item to true or false depending on whether it's truthy or falsy. If the item is truthy, we keep it.

Can you use == for Boolean in Java?

Typically, you use == and != with primitives such as int and boolean, not with objects like String and Color. With objects, it is most common to use the equals() method to test if two objects represent the same value.

What is the difference between findFirst and findAny Java 8?

The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.

How do I filter a String in Java 8?

Using Java 8 In Java 8 and above, use chars() or codePoints() method of String class to get an IntStream of char values from the given sequence. Then call the filter() method of Stream for restricting the char values to match the given predicate.


1 Answers

Sounds like a straightforward or condition to me.

.filter(number -> !ignoreEven || (number % 2 != 0))
like image 148
Joe C Avatar answered Sep 17 '22 18:09

Joe C