Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda predicate chaining?

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?

like image 453
user1606576 Avatar asked Jun 24 '14 21:06

user1606576


People also ask

What method can be used to chain two Predicate in Java 8?

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().

How do you add multiple predicates in Java?

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.

Which method of the Java Util function Predicate interface allows you to chain two predicates?

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.


1 Answers

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") 
like image 81
Chris Jester-Young Avatar answered Nov 05 '22 01:11

Chris Jester-Young