IntPredicate interface
IntPredicate
is a Functional Interface added in java 8 and is a specialization of java Predicate for integer values.
IntPredicate
represents an expression used to check integer values and returns true
or false
if the values match or not respectively.
IntPredicate
works for integer values only.
As stated above,
IntPredicate
is a Functional Interface and hence it can be represented as a Lambda expression as shown below.
IntPredicate greaterThan = num -> num > 20;
Here, IntPredicate
is assigned a Lambda expression which checks if its argument is greater than 20. num is a variable that is local to Lambda expression and need not be declared before using it.
IntPredicate
has a single method test()
which takes an integer argument and test this value against the predicate condition. Example,
IntPredicate greaterThan = num -> num > 20; boolean result = greaterThan.test(50); // returns true
In this example, test()
will check if 50 is greater than 20.
Chaining IntPredicate
It is possible to check complex conditions by chaining Predicates such as checking if a number lies between a range, less than or equal to a threshold etc.
IntPredicate
has methods such as and()
, or()
that allow combining multiple predicates together. This chaining works the same way as using logical AND(&&
) or OR(||
) operators.
Example, suppose you want to check if a number lies between 100 and 999. With predicate chaining, this can be done as below.
IntPredicate lower = num -> num >= 100; IntPredicate higher = num -> num <= 999; IntPredicate range = lower.and(higher); boolean result = range.test(500); // returns true
and()
combines the predicates and the condition will evaluate true only when both the predicates return true
.
Similarly, or()
method is also used to combine predicates. In that case, if any one predicate returns true
, the result of evaluation is true
.
IntPredicate negate
IntPredicate
has a negate()
method which is used to reverse its result. It is similar to applying a NOT(!
) before a condition.
Example, if you want to check if a number is greater than 0, then using negate()
, it can be written as
// predicate for greater than 0 IntPredicate positive = num -> num > 0; // reverse it boolean result = positive.negate().test(5); // returns false
Note that IntPredicate
is a Functional Interface having only one abstract method test()
. All other methods such as and()
. or()
, negate()
are default interface methods which are defined in the interface itself.