Java 8 - IntPredicate interface example

Posted on December 1, 2016


java.util.function.IntPredicate is a functional interface whose functional method is boolean test(int a). The IntPredicate interface represents an operation that takes a single argument of int type and returns a boolean result.

Example #1

The following example shows how to use the test() method of the IntPredicate interface with lambda expression.

IntPredicateExample1.java

package com.boraji.tutorial.lambda;

import java.util.function.IntPredicate;

/**
 * @author imssbora
 */
public class IntPredicateExample1 {
	public static void main(String[] args) {
		IntPredicate predicate = a -> a > 0;
		System.out.println(predicate.test(5));
		System.out.println(predicate.test(-5));
	}
}

Output

true
false

Example #2

The following example shows how to use the default methods (and(), or() and negate()) of the IntPredicate interface with lambda expression.

IntPredicateExample2.java

package com.boraji.tutorial.lambda;

import java.util.function.IntPredicate;

/**
 * @author imssbora
 */
public class IntPredicateExample2 {
	public static void main(String[] args) {
		IntPredicate predicate1 = a -> a > 0;
		IntPredicate predicate2 = a -> a == 10;

		// Using and()
		System.out.println(predicate1.and(predicate2).test(5));

		// Using or()
		System.out.println(predicate1.or(predicate2).test(12));

		// Using negate()
		System.out.println(predicate2.negate().test(10));

	}
}

Output

false
true
false