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


ToIntFunction<T> is the built-in functional interface defined in java.util.function package. This functional interface expects an argument as input and produces an int-valued result. It can be used as an assignment target for a lambda expression or method reference. The ToIntFunction interface holds only one method, applyAsInt(). This method performs an operation on the given argument and returns the int-valued result.

Syntax

@FunctionalInterface
public interface ToIntFunction {
   int applyAsInt(T value);
}

In the below example, we can implement ToIntFunction<T> by using lambda expression and method reference.

Example

import java.util.function.ToIntFunction;
import java.time.LocalDate;

public class ToIntFunctionInterfaceTest {
   public static void main(String[] args) {
      ToIntFunction<Integer> lambdaObj = value -> value * 25;   // using lambda expression
      System.out.println("The result is: " + lambdaObj.applyAsInt(10));

      ToIntFunction<String> lenFn = String::length;   // using method reference
      System.out.println("The length of a String is: " + lenFn.applyAsInt("tutorialspoint"));
   }  
}

Output

The result is: 250
The length of a String is: 14

Updated on: 13-Jul-2020

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements