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


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

Updated on: 14-Jul-2020

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements