Sobes.tech
Middle

What are the functional interfaces ToDoubleFunction<T>, ToIntFunction<T>, and ToLongFunction<T> used for in Java?

sobes.tech AI

Answer from AI

These interfaces from the java.util.function package are used for converting an object of type T into a primitive type:

  • ToDoubleFunction<T>: Converts an object of type T into a double.
  • ToIntFunction<T>: Converts an object of type T into an int.
  • ToLongFunction<T>: Converts an object of type T into a long.

The main purpose is to be used in Stream API, collections, and other contexts where it is necessary to perform calculations or extract a primitive numeric value from objects.

Example of usage with Stream API:

import java.util.Arrays;
import java.util.List;
import java.util.function.ToDoubleFunction;

public class Example {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "cherry");

        // ToDoubleFunction to determine the length of the string as a double
        ToDoubleFunction<String> lengthAsDouble = s -> (double) s.length();

        double averageLength = words.stream()
                                    .mapToDouble(lengthAsDouble)
                                    .average()
                                    .orElse(0.0);

        System.out.println(averageLength);
    }
}