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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 27-Jan-2020 14:11:08
Advertisements