ToIntFunction Interface in Java with Examples

The java.util.function package, which was introduced with Java 8, includes the ToIntFunction Interface, which is used to implement functional programming in the language. It is a representation of a function that accepts a type T parameter and outputs an integer value.

There is only one generic accepted by this functional interface, which is:

T: indicates the kind of argument used as an input for the operation.

The defineAsInt() function of an object of the ToIntFunction type uses the lambda expression passed to it to apply the specified operation to its single parameter. Using an object of type Function<T, Integer> is similar to this. There is just one function for the ToIntFunction interface, which is applyAsInt(). The function is applied to the given argument in this method, and the int type result is returned. This is how the interface operates functionally.

Syntax:

Parameters: The single parameter value that this method accepts is an argument of type T.

Returns: An int-valued result is obtained by this method.

Example 1:

The given program shows how to utilize the ToIntFunction interface from the Java java.util.function library. A lambda expression that takes a String and returns its length is used to instantiate a ToIntFunction<String> inside the main method. The text "Hello, Welcome to the World!" is then passed as an argument to the ToIntFunction's applyAsInt method, which determines and returns the string's length. Lastly, the string's length is displayed on the console, demonstrating how operations on a string can be carried out using the ToIntFunction interface, resulting in an integer result.

Implementation:

FileName: TolntExample1.java

Output:

The length of the string is: 27

Example 2:

The given program shows how to determine the total length of a list of strings by using Java Streams and the ToIntFunction interface. Programming languages are produced in a list of strings that are created in the main procedure. The length of each string is determined by the String class's length method, which is referenced when defining a ToIntFunction<String>. Next, the program maps each string in the list to its length using Java Streams and then adds up these lengths. In the end, the entire length of all the strings is displayed on the console, demonstrating the efficient use of ToIntFunction with streams for these kinds of aggregate tasks.

Implementation:

FileName: TolntExample2.java

Output:

The total length of all the given strings is : 24