Java 8 Examples

Predicate interface in Java 8 with examples

Posted On
Posted By admin

In this blog post, I will be explaining how the Java 8 functional interface Predicate works. To know more about functional interfaces, you can refer this blog post.

The Predicate interface provides a method called test. This method accepts a parameter of any data type and returns a boolean.

Predicate method with Integer argument

Consider the following code snippet:

public class PredicateDemo {

public static void main(String[] args) {
Predicate<Integer> greaterThan8 = (input) -> input > 8;
System.out.println("4 is greater than 8 = "+greaterThan8.test(4));
System.out.println("12 is greater than 8 = "+greaterThan8.test(12));
}

}

Here, the Predicate.test method checks if the input number is greater than 8. So when the above code is executed, it will print the following output:

4 is greater than 8 = false
12 is greater than 8 = true

Predicate method with String argument

Consider the following code snippet:


import java.util.function.Predicate;

public class PredicateDemo {

public static void main(String[] args) {
Predicate<String> startsWithHello = (str) -> str.startsWith("Hello");
System.out.println("Hello World starts with Hello = "+startsWithHello.test("Hello World"));
System.out.println("Test String starts with Hello = "+startsWithHello.test("Test String"));

}

}

Here, the Predicate.test method checks if the input String starts with the String “Hello”. So when the above code is executed, it will print the following output:

Hello World starts with Hello = true 
Test String starts with Hello = false

You can get the source code for this example along with the code for other Java 8 examples at the Github repository here.


If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my new course Learn Java 8 New Features

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment