How to implement LongPredicate using lambda and method reference in Java?

Java 8Object Oriented ProgrammingProgramming

LongPredicate is a functional interface defined in java.util.function package. This interface can be used mainly for evaluating an input of type long and returns an output of type boolean. LongPredicate can be used as an assignment target for a lambda expression or method reference. It contains one abstract method: test() and three default methods: and(), negate() and or().

Syntax

@FunctionalInterface
interface LongPredicate {
 boolean test(long value);
}

Example of Lambda Expression

import java.util.function.LongPredicate;

public class LongPredicateLambdaTest {
   public static void main(String args[]) {
      LongPredicate longPredicate = (long input) -> {    // lambda expression
         if(input == 50) {
            return true;
         } else
            return false;
      };
      boolean result = longPredicate.test(50);
      System.out.println(result);
   }
}

Output

true


Example of method reference

import java.util.function.LongPredicate;

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

Output

false
raja
Published on 21-Jan-2020 17:28:25
Advertisements