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


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
raja

e

Updated on: 16-Jan-2020

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements