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

Java 8Object Oriented ProgrammingProgramming

LongToIntFunction is a functional interface from java.util.function package introduced in Java 8. This functional interface accepts a long-valued parameter as input and produces an int-valued result. LongToIntFunction interface can be used as an assignment target for a lambda expression or method reference. This interface contains only one abstract method: applyAsInt() and doesn't contain any default and abstract methods.

Syntax

@FunctionalInterface
interface LongToIntFunction {
   int applyAsInt(long value);
}

Example of Lambda Expression

import java.util.function.LongToIntFunction;

public class LongToIntLambdaTest {
   public static void main(String args[]) {
      LongToIntFunction getInt = longVal -> {     // lambda expression
         int intVal = (int)longVal;
         return intVal;
      };

      long input = 757775L;
      System.out.println("The input is: " + input);

      int result = getInt.applyAsInt(input);
      System.out.println("The result is: " + result);
   }
}

Output

The input is: 757775
The result is: 757775


Example of Method Reference

import java.util.function.LongToIntFunction;

public class LongToIntFunctionMethodRefTest {
   public static void main(String[] args) {
      LongToIntFunction result = LongToIntFunctionMethodRefTest::convertLongToInt;  // method reference
      System.out.println(result.applyAsInt(50));
      System.out.println(result.applyAsInt(100));
   }
   static Integer convertLongToInt(long value) {
      return (int) value / 10;
   }
}

Output

5
10
raja
Published on 27-Jan-2020 17:29:00
Advertisements