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


IntToLongFunction is a built-in functional interface from java.util.function package. This functional interface accepts an int-valued parameter and produces a long-valued result. IntToLongFunction interface can be used as an assignment target for a lambda expression or method reference. It contains only one abstract method: applyAsLong().

Syntax

@FunctionalInterface
interface IntToLongFunction {
 long applyAsLong(int value);
}

Example of Lambda Expression

import java.util.function.IntToLongFunction;

public class IntToLongFunctionLambdaTest {
   public static void main(String args[]) {
      IntToLongFunction getLong = intVal -> {      // lambda expression
         long longVal = intVal;
         return longVal;
      };
   
      int input = 40;
      long result = getLong.applyAsLong(input);
      System.out.println("The long value is: " + result);

      input = 75;
      System.out.println("The long value is: " + getLong.applyAsLong(input));

      input = 90;
      System.out.println("The long value is: " + getLong.applyAsLong(input));
   }
}

Output

The long valus is: 40
The long valus is: 75
The long valus is: 90


Example of Method Reference

import java.util.function.IntToLongFunction;

public class IntToLongFunctionMethodRefTest {
   public static void main(String args[]) {
      IntToLongFunction result = IntToLongFunctionMethodRefTest::convertIntToLong;   // method reference
      System.out.println(result.applyAsLong(75));
      System.out.println(result.applyAsLong(45));
   }
   static Long convertIntToLong(int value) {
      return value / 10L;
   }
}

Output

7
4

Updated on: 15-Jul-2020

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements