ToIntBiFunction Interface in Java with Examples

The java.util.function package, which was introduced with Java 8, contains the ToIntBiFunction Interface, which is used to implement functional programming in Java. It is a representation of a function that accepts two inputs of type T and U and returns an integer value.

There are two generics that this functional interface accepts:

T stands for the type of the operation's first input argument.

U: The type of the operation's second input argument is indicated by U.

The defineAsInt() function of an object of the ToIntBiFunction type uses the lambda expression passed to it to perform the specified operation to its two parameters at the end. It is comparable to utilizing a BiFunction<T, U, Integer> object.

The ToIntBiFunction interface serves just one function that is applyAsInt().

This function returns an int-valued result and takes two arguments of type T and U.

Syntax:

Parameters: This method has particularly two parameters which are:

t - the first input argument parameter

u - the second input argument parameter

Returns: An integer result is returned by this method.

Example 1:

An example of using the ToIntBiFunction interface to generate a lambda expression that accepts an integer and a string as inputs and returns an int result is given in the below Java program. The String is converted to an integer using the lambda function described in the ToIntBiFunction, which then multiplies the result by 4 and adds it to the first integer parameter. Then, given the inputs "10" and "4", the applyAsInt method is invoked, resulting in the calculation 4 + (10 × 4) = 44.

Implementation:

FileName: ApplyasIntmethodExample1.java

Output:

The value is given by: 44

Example 2:

The Java program that is given demonstrates how to compute the difference in lengths between two strings using the ToIntBiFunction interface. Within the ToIntBiFunction, there is a defined lambda expression that takes two strings as inputs and returns the difference in lengths between them by subtracting the second string's length from the first. Then, two separate instances of the applying method are called: once with the strings "hello" and "world," resulting in a length difference of 0, and again with "Welcome" and "Thanks," resulting in a length difference of 1.

Implementation:

FileName: DiffInStringsLength.java

Output:

The Length Difference between the Strings is : 0
The Length Difference between the Strings is : 1