3

Java streams' filters use Predicates to allow or deny an element through the stream.

Thanks to .compose or .andThen the filter can be restricted.

Yet what if I wanted to have it more permissive according to some flags?

For example, I might want to have isAppleAllowed and isPearAllowed parametrically set by the user.

The use of .filter(f -> isAppleAllowed || isPearAllowed) doesn't work, because if either is True, both are allowed.

What can I use to extend the filter more permissively?

Thanks in advance for any help.

3 Answers3

2

Your example doesn't make sense. If isAppleAllowed and isPearAllowed are boolean parameters, as their names and your prose seem to indicate, then neither those individually nor any boolean combination of the two constitutes a predicate you can use for applying the filtering they describe. You would instead want something along the lines of

fruitStream.filter(f -> { return f.isApple() && isAppleAllowed; })

to filter for apples, and similar for pears. To filter jointly, you could use

fruitStream.filter(f -> {
    return (f.isApple() && isAppleAllowed)
            ||  (f.isPear() && isPearAllowed);
})

Alternatively, given two Predicate<Fruit> objects, say applePredicate and pearPredicate, class Predicate provides methods for forming joint predicates:

fruitStream.filter(applePredicate.or(pearPredicate))
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

I had to change this answer, because what you're looking for was different than what I originally answered. Using two separate calls to Stream#filter, as I previously suggested, wouldn't make sense, as both Predicates would need to rely on each other in that case.

.filter(f -> (f.isApple() && isAppleAllowed) || (f.isPear() && isPearAllowed))

Something like this should work though, as it checks the attributes of the element before attempting to filter it. Assuming the element can be either an apple or a pear, then it will be filtered through if isAppleAllowed or isPearAllowed is true, respectively.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
1

You can create an helper function that will return Predicate for you. Within this function, you can use both of your boolean function.

Roni Koren Kurtberg
  • 495
  • 1
  • 8
  • 18