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

Java 8Object Oriented ProgrammingProgramming

DoublePredicate is a built-in functional interface defined in java.util.function package. This interface can accept one double-valued parameter as input and produces a boolean value as output. DoublePredicate interface can be used as an assignment target for a lambda expression or method reference. This interface contains one abstract method: test() and three default methods: and(), or() and negate().

Syntax

@FunctionalInterface
public interface DoublePredicate {
   boolean test(double value)
}

Example of lambda expression

import java.util.function.DoublePredicate;

public class DoublePredicateLambdaTest {
   public static void main(String args[]) {
      DoublePredicate doublePredicate = (double input) -> {    // lambda expression
         if(input == 2.0) {
            return true;
         } else
            return false;
      };
      boolean result = doublePredicate.test(2.0);
      System.out.println(result);
   }
}

Output

true


Example of method reference

import java.util.function.DoublePredicate;

public class DoublePredicateMethodRefTest {
   public static void main(String[] args) {
      DoublePredicate doublePredicate = DoublePredicateMethodRefTest::test;  // method reference
      boolean result = doublePredicate.test(5.0);
      System.out.println(result);
   }
   static boolean test(double input) {
      if(input == 5.0) {
         return true;
      } else
         return false;
   }
}

Output

true
raja
Published on 16-Jan-2020 14:34:48
Advertisements