In Java 8 java.util.function package you will find the Predicate.java Functional Interface which is a boolean-valued function which takes one argument and returns a boolean, lets see some examples,
Java Predicate Examples:- 1: Check if provided input is of type String
- 2: Check if provided input is of null
- 3: Check if provided input String is declared
- 4: Check if age is over 18 or not
- 5: Check if array contains inputted String.
- 6: Check if provided input has length > 4 or not
- 7: Predicate with changing with default or method
- 8: Predicate with Stream filter
Example 1:
package org.code2care;
import java.util.function.Predicate;
/**
*
* Use of Predicate to check if the provided input
* to test function is a String or not
*
*/
public class PredicateExample1 {
public static void main(String[] args) {
String string = "Java";
int integer = 10;
Boolean bool = true;
Predicate<Object> isString = object -> (object instanceof String);
System.out.println(isString.test(string));
System.out.println(isString.test(integer));
System.out.println(isString.test(bool));
}
}
Output:
true
false
false
Example 2:
package com.company;
import java.util.function.Predicate;
/**
*
* Use of Predicate to check if the provided input
* as is null or not
*
*/
public class PredicateExample2 {
public static void main(String[] args) {
String str1 = null;
String str2 = "Java";
Predicate<Object> isDefined = s -> (s == null);
System.out.println(isDefined.test(str1));
System.out.println(isDefined.test(str2));
}
}
Output:
true
false
Example 3:
package com.company;
import java.util.function.Predicate;
/**
*
* Use of Predicate to check if the provided input
* to declared or not
*
*/
public class PredicateExample3 {
public static void main(String[] args) {
String str1 = null;
String str2 = " ";
String str3 = "";
String str4 = "Java";
Predicate<String> isDefined = s -> (s == null || "".equals(s.trim()));
System.out.println(isDefined.test(str1));
System.out.println(isDefined.test(str2));
System.out.println(isDefined.test(str3));
System.out.println(isDefined.test(str4));
}
}
Output:
true
true
true
false
Example 4:
package com.company;
import java.util.function.Predicate;
/**
*
* Use of Predicate to check if the provided input
* as age is greater than 18 or not
*
*/
public class PredicateExample4 {
public static void main(String[] args) {
int age1 = 12;
int age2 = 18;
int age3 = 22;
Predicate<Integer> isAbove18 = s -> (s > 18);
System.out.println(isAbove18.test(age1));
System.out.println(isAbove18.test(age2));
System.out.println(isAbove18.test(age3));
}
}
Output:
false
false
true
Example 5:
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
*
* Use of Predicate to check if the provided input
* is available in a Collection List or not
*
*/
public class PredicateExample5 {
public static void main(String[] args) {
List<String> countries = new ArrayList<>();
countries.add("Japan");
countries.add("China");
countries.add("USA");
countries.add("France");
countries.add("Australia");
countries.add("Sweden");
Predicate<String> isInCountriesList = country -> (countries.contains(country));
String country1 = "Canada";
String country2 = "India";
String country3 = "Sweden";
System.out.println(isInCountriesList.test(country1));
System.out.println(isInCountriesList.test(country2));
System.out.println(isInCountriesList.test(country3));
}
}
Output:
false
false
true
Example 6:
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
*
* Use of Predicate to check if the provided input
* has the length as required
*
*/
public class PredicateExample6 {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Python";
String s3 = "PHP";
String s4 = "Scala";
String s5 = "Swift";
Predicate<String> isLengthGreaterThan4 = string -> (string.length() > 4);
System.out.println(isLengthGreaterThan4.test(s1));
System.out.println(isLengthGreaterThan4.test(s2));
System.out.println(isLengthGreaterThan4.test(s3));
System.out.println(isLengthGreaterThan4.test(s4));
System.out.println(isLengthGreaterThan4.test(s5));
}
}
Output:
false
false
false
true
true
Example 7:
package com.company;
import java.util.function.Predicate;
/**
*
* Predicate With Chaining with or default function
*
*/
public class PredicateExample7 {
public static void main(String[] args) {
String s1 = "Cool";
String s2 = "Dude";
String s3 = "Awesome";
Predicate<String> startsWithC = (string) -> (string.toLowerCase().startsWith("c"));
Predicate<String> startsWithD = (string) -> (string.toLowerCase().startsWith("d"));
Predicate<String> startsWithCorD = startsWithC.or(startsWithD);
System.out.println(startsWithCorD.test(s1));
System.out.println(startsWithCorD.test(s2));
System.out.println(startsWithCorD.test(s3));
}
}
Output:
true
true
false
Example 8:
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* Predicate with Stream filter
*
*/
public class PredicateExample8 {
public static void main(String[] args) {
Employee emp1 = new Employee(1,"John",34,2000);
Employee emp2 = new Employee(2,"Alex",22,5000);
Employee emp3 = new Employee(3,"Brian",23,5000);
Employee emp4 = new Employee(3,"Bob",23,7500);
List<Employee> employeeList = new ArrayList<>();
employeeList.add(emp1);
employeeList.add(emp2);
employeeList.add(emp3);
employeeList.add(emp4);
ArrayList<Employee> allEmpWithAgeGt22AndNameStartWithB = (ArrayList<Employee>) employeeList.stream().filter(emp -> emp.getEmpAge() > 22 && emp.getEmpName().startsWith("B")).collect(Collectors.toList());
for (Employee emp: allEmpWithAgeGt22AndNameStartWithB) {
System.out.println(emp.getEmpName()+","+emp.getEmpAge()+","+emp.getEmpSalary());
}
}
static class Employee {
int empId;
String empName;
int empAge;
int empSalary;
public Employee(int empId, String empName, int empAge, int empSalary) {
this.empId = empId;
this.empName = empName;
this.empAge = empAge;
this.empSalary = empSalary;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpAge() {
return empAge;
}
public void setEmpAge(int empAge) {
this.empAge = empAge;
}
public int getEmpSalary() {
return empSalary;
}
public void setEmpSalary(int empSalary) {
this.empSalary = empSalary;
}
}
}

More Posts related to Java,
- Convert Java Map Collection Object to JSON String using Jackson
- Java Stream flatmap() Examples
- [Fix] Instant java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years
- How to run Java Unit Test cases with Apache Maven?
- How to check if Java main thread is alive
- [Fix] java: incompatible types: incompatible parameter types in lambda expression error
- Parsing CSV file using Java code example (Comma Separated File)
- Unhandled exception type InterruptedException : Java Threads
- Native getClass() method from java.lang.Object Class Explained with examples.
- Java Jackson ObjectMapper Class with Examples
- Java 8 Streams map() with examples
- Java 8 - Convert List to Map Examples
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- Java Stream with Multiple Filters Example
- How to Clear StringJoiner in Java 8
- Spring 5 IoC Example with application Context XML (ClassPathXmlApplicationContext) and Gradle.
- How to get end of line (EOL) or new line character \r \n in Java
- Spring Boot CRUD Examples using JDBCTemplate
- Delete a File in Java with Examples
- Implementing Insertion Sort Algorithm in Java Program
- Java JDBC Batch Update Example with PreparedStatement
- Java JDBC Select Multiple Records from table as List using PreparedStatement
- [Hibernate] The method buildSessionFactory() from the type Configuration is deprecated
- How to fix Java HTTP java.net.UnknownHostException
- Java 8 Display time in 12 hour AM PM format
More Posts:
- Where does Notepad++ save temp files? - NotepadPlusPlus
- Android Installation error: INSTALL_FAILED_OLDER_SDK on Device - Android
- [Docker] Install Git on Alpine Linux - Docker
- How to Install Git on Ubuntu Linux - Git
- SharePoint - The URL is invalid. It may refer to a nonexistent file or folder, or refer to a valid file or folder that is not in the current Web. - SharePoint
- How to fully uninstall Conda on Windows - HowTos
- PHP Base64 encoding decoding a variable - PHP
- Limit scrollback rows in macOS Terminal - MacOS