I can't get it to compile, is it even possible to chain predicate lambdas?
Arrays.asList("1","2","3").stream().filter( (e -> e=="1" ).or(e-> e=="2") ).count();
Or only way is to explicitly create a predicate and then combine like so:
Predicate<String> isOne= e -> e=="1"; Arrays.asList("1","2","3").stream().filter( isOne.or(e -> e=="2") ).count();
Or is there more "functionally elegant" way to achieve same thing?
Next, if we don't want to build a complex Predicate using bitwise operations, Java 8 Predicate has useful methods that we can use to combine Predicates. We'll combine Predicates using the methods Predicate. and(), Predicate.or(), and Predicate. negate().
Use negate() to write the reverse/negative conditions so that a single predicate may serve true and false – both scenarios. Use and() to combine two predicates for a logical AND operation. Use or() to combine two predicates for a logical OR operation.
The and() method returns a composed predicate that represents a short-circuiting logical AND of given predicate and another. When evaluating the composed predicate, if the first predicate is false , then the other predicate is not evaluated.
You can use:
((Predicate<String>) e -> e.equals("1")).or(e -> e.equals("2"))
but it's not very elegant. If you're specifying the conditions in-line, just use one lambda:
e -> e.equals("1") || e.equals("2")
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