Java Lambda Predicate Example

Java 8 has provided Predicate functional interface which can be use to evaluate values from object or compare primitive type. You can also include multiple condition to Predicate interface. To understand please see example below:

  • LambdaPredicate.java:
package com.javahonk;

import java.util.function.Predicate;

public class LambdaPredicate {

	public static void main(String[] args) {
		
		//Example 1
		
		Person person = new Person(35, "Male", "Java", "Honk");
		
		//Will print true
		Boolean result = getValue().test(person);
		System.out.println("Predicate person result: "+result);
		
		//Example 2
		
		Predicate<Double> greaterThanTest = (e) -> e > 22.3;
		// Will print false
		result = greaterThanTest.test(14.0);
		System.out.println("Predicate result: "+result);
		
		//Example 3
		//Pass predicate as method parameter
		result = compareVale(20, (value) -> value > 17);
		System.out.println("Predicate result: "+result);

	}
	
    private static Predicate<Person> getValue(){
    	return p -> p.getAge() > 34 && p.getGender().equalsIgnoreCase("Male");
    	
    }
    
    private static Boolean compareVale(int number, Predicate<Integer> predicate) {    	  
    	return predicate.test(number);
    }
}

class Person {

	private Integer age;
	private String gender;
	private String firstName;
	private String lastName;
	
	public Person(Integer age, String gender, String firstName, String lastName) {
		super();
		this.age = age;
		this.gender = gender;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public Integer getAge() {
		return age;
	}
	public String getGender() {
		return gender;
	}
	public String getFirstName() {
		return firstName;
	}
	public String getLastName() {
		return lastName;
	}
}
  • Output:

Java Lambda Predicate Example

  • For more information please visit Oracle example here

Leave a Reply

Your email address will not be published. Required fields are marked *