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

Java 8Object Oriented ProgrammingProgramming

LongSupplier is a built-in functional interface from java.util.function package. This interface doesn’t expect any input but produces a long-valued output. Since LongSupplier is a functional interface, it can be used as an assignment target for lambda expression and method reference and contains only one abstract method: getAsLong().

Syntax

@FunctionalInterface
public interface LongSupplier {
 long getAsLong();
}

Example of Lambda Expression

import java.util.function.LongSupplier;

public class LongSupplierLambdaTest {
   public static void main(String args[]) {
      LongSupplier supplier = () -> {     // lambda expression
         return 75;
      };
      long result = supplier.getAsLong();
      System.out.println(result);
   }
}

Output

75


Example of method reference

import java.util.function.LongSupplier;
public class LongSupplierMethodRefTest {
   public static void main(String[] args) {
      LongSupplier supplier = LongSupplierMethodRefTest::getValue; // method reference
      double result = supplier.getAsLong();
      System.out.println(result);
   }
   static long getValue() {
      return 50;
   }
}

Output

50.0
raja
Published on 22-Jan-2020 12:13:36
Advertisements