How do I use the ToIntFunction functional interface in Java?

The ToIntFunction functional interface in Java is part of the java.util.function package and represents a function that accepts one argument and produces a int-valued result. It is a functional interface with a single abstract method int applyAsInt(T value), making it a good candidate for usage in lambda expressions or method references.

Here’s how to use the ToIntFunction:


Syntax

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

Example Use Cases

1. Example with a Lambda Expression

We might use ToIntFunction to transform an object to a corresponding primitive int, such as when mapping a property to an int.

package org.kodejava.util.function;

import java.util.function.ToIntFunction;

public class ToIntFunctionExample {
    public static void main(String[] args) {
        // A sample lambda expression that converts a String length to an int
        ToIntFunction<String> stringLengthFunction = str -> str.length();

        // Example usage:
        String test = "Hello, World!";
        int length = stringLengthFunction.applyAsInt(test);

        System.out.println("The length of the string \"" + test + "\" is: " + length);
    }
}

Output:

The length of the string "Hello, World!" is: 13

2. Example with Method Reference

We can also pass a method reference that produces an int from an object.

package org.kodejava.util.function;

import java.util.function.ToIntFunction;

public class ToIntFunctionExample2 {
    public static void main(String[] args) {
        // Using a method reference for String.length()
        ToIntFunction<String> stringLengthFunction = String::length;

        // Example usage:
        String test = "Functional Interface!";
        int length = stringLengthFunction.applyAsInt(test);

        System.out.println("The length of \"" + test + "\" is: " + length);
    }
}

3. Example in a Stream

ToIntFunction can be particularly useful when working with streams where we want to produce primitive int results.

package org.kodejava.util.function;

import java.util.Arrays;
import java.util.List;

public class ToIntFunctionStreamExample {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("Java", "Code", "Stream", "Example");

        // Using the mapToInt method of the Stream API
        int totalLength = words.stream()
                .mapToInt(String::length) // Use ToIntFunction
                .sum();

        System.out.println("Total length of all words: " + totalLength);
    }
}

Output:

Total length of all words: 22

Key Points:

  1. ToIntFunction is suitable when we need to transform an object into a primitive int.
  2. Use it wherever we need a concise way of defining an operation resulting in an int (e.g., extracting numeric data, calculating lengths, etc.).
  3. Works perfectly with Java’s functional programming features like lambda expressions, method references, and streams.

This makes ToIntFunction a powerful tool for reducing boilerplate code when working with primitive int values in Java programs.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.