Java 8 Predicate examples

Previous
Next

Java 8 predicates are functional interface introduced in java 8.
Predicate is single argument function which returns true or false. It has test method which returns true or false.
For example:

So when you run above predicate logic, it will return true.
You can pass Predicate as a function argument too.

Filter list using predicate:

Java 8 stream’s function takes Predicate as a argument and can be used to filter the list with the help of predicates.
Lets say you have student class as below:

Lets create a function which will be used to filter students based on predicates.

Lets create a main class as below:

When you run above program, you will get below output:

18 are :[Student [id=1, name=Arpit, gender=M, age=19], Student [id=4, name=Martin, gender=M, age=21]]

Female students having age < 18 are :[Student [id=3, name=Mary, gender=F, age=14], Student [id=5, name=Monica, gender=F, age=16]]

That’s all about Java 8 Predicate example

Previous
Next

Add Comment