Java.Java8.What are the functional interfaces ToDoubleFunction, ToIntFunction, and ToLongFunction?

Let’s now explore the ToDoubleFunction<T>, ToIntFunction<T>, and ToLongFunction<T> functional interfaces. These are used when you want to map an object of type T to a primitive (double, int, or long) — without boxing.

✅ 1. ToDoubleFunction<T>

@FunctionalInterface
public interface ToDoubleFunction<T> {
    double applyAsDouble(T value);
}

🧠 Example:

ToDoubleFunction<String> lengthTimesPi = s -> s.length() * Math.PI;

System.out.println(lengthTimesPi.applyAsDouble("Java")); // Output: ~12.57

✅ Use Case:

  • Works perfectly with .mapToDouble() in streams:
Stream<String> words = Stream.of("hello", "world");
double sum = words.mapToDouble(lengthTimesPi).sum();

✅ 2. ToIntFunction<T>

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

🧠 Example:

ToIntFunction<String> stringLength = String::length;

System.out.println(stringLength.applyAsInt("banana")); // Output: 6

✅ Use Case:

List<String> fruits = List.of("apple", "banana", "pear");

int totalChars = fruits.stream()
    .mapToInt(stringLength)
    .sum();

✅ 3. ToLongFunction<T>

@FunctionalInterface
public interface ToLongFunction<T> {
    long applyAsLong(T value);
}

🧠 Example:

ToLongFunction<String> charValueSum = s ->
    s.chars().asLongStream().sum();

System.out.println(charValueSum.applyAsLong("abc")); // Output: 97 + 98 + 99 = 294

✅ Use Case:

Used with .mapToLong():

Stream<String> data = Stream.of("abc", "xyz");
long total = data.mapToLong(charValueSum).sum();

🔄 Summary Table

InterfaceInput TypeReturn TypeUse Case
ToDoubleFunction<T>Tdouble.mapToDouble() in streams
ToIntFunction<T>Tint.mapToInt() in streams
ToLongFunction<T>Tlong.mapToLong() in streams

💡 Why use these?

  • Avoid boxing (Integer, Double, Long)
  • Better performance in streams
  • Cleaner syntax for numeric pipelines
This entry was posted in Без рубрики. Bookmark the permalink.