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
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.
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.
The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.
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.
Sounds like a straightforward or condition to me.
.filter(number -> !ignoreEven || (number % 2 != 0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With