How to implement the IntPredicate interface using lambda and method reference in Java?

Java 8Object Oriented ProgrammingProgramming

IntPredicate interface is a built-in functional interface defined in java.util.function package. This functional interface accepts one int-valued argument as input and produces a boolean value as an output. This interface is a specialization of the Predicate interface and used as an assignment target for a lambda expression or method reference. It provides only one abstract method, test ().

Syntax

@FunctionalInterface
public interface IntPredicate {
 boolean test(int value);
}

Example for Lambda Expression

import java.util.function.IntPredicate;

public class IntPredicateLambdaTest {
   public static void main(String[] args) {
      IntPredicate intPredicate = (int input) -> {   // lambda expression
         if(input == 100) {
            return true;
         } else
            return false;
      };
      boolean result = intPredicate.test(100);
      System.out.println(result);
   }
}

Output

true


Example for Method Reference

import java.util.function.IntPredicate;

public class IntPredicateMethodReferenceTest {
   public static void main(String[] args) {
      IntPredicate intPredicate = IntPredicateMethodReferenceTest::test;   // method reference
      boolean result = intPredicate.test(100);
      System.out.println(result);
   }
   static boolean test(int input) {
      if(input == 50) {
         return true;
      } else
         return false;
   }
}

Output

false
raja
Published on 09-Jan-2020 16:07:18
Advertisements