Course contentsShow
← Java
Lesson 1693 of 2,87035. Functional InterfacesFree lesson

ToIntFunction, ToLongFunction, and ToDoubleFunction

Use functions that accept objects and return primitives, avoiding boxing on the return path.

ToIntFunction, ToLongFunction, and ToDoubleFunction

What you'll learn: How to use specialized functional interfaces that convert objects into primitive numbers without the performance cost of boxing.

The Problem They Solve

When you need to transform an object into a primitive number (int, long, or double), you could use Function<T, Integer>, but that forces Java to wrap the result in an Integer wrapper object—a process called boxing. These three interfaces let you skip that overhead entirely by returning primitives directly.

The Three Interfaces

Each interface takes a generic object type and returns a specific primitive:

  • ToIntFunction<T> – converts T to int via applyAsInt(T value)
  • ToLongFunction<T> – converts T to long via applyAsLong(T value)
  • ToDoubleFunction<T> – converts T to double via applyAsDouble(T value)

Think of It Like This

Imagine you're running a factory where objects come in and numbers go out. You could package each number in a gift box before it leaves (Function<T, Integer>), but that's wasteful when you could just hand over the raw number (ToIntFunction<T>). Same result, less wrapping paper.

Why This Matters

These interfaces are commonly used as arguments in Stream operations and collectors where extracting numeric values is needed:

// Where you've seen them before:
Collectors.summingInt(ToIntFunction<? super T> mapper)
Collectors.averagingDouble(ToDoubleFunction<? super T> mapper)

They're the reason those operations can aggregate millions of values efficiently—no boxing means less memory allocation and faster execution.

Key Takeaway: Use ToIntFunction, ToLongFunction, and ToDoubleFunction when you need to extract primitive numeric values from objects—they avoid boxing on the return path, making your code faster and more memory-efficient than generic Function alternatives.