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: 2020-07-14T12:25:24+05:30

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements