Java.Java8.What are the functional interfaces Function, DoubleFunction, IntFunction, and LongFunction?

Let’s break down Function<T, R> and DoubleFunction<R> — they’re both part of the java.util.function package and are used to represent functions as objects in Java.


Function<T, R>

➤ Signature:

R apply(T t);

➤ Meaning:

  • Takes an input of type T
  • Returns a result of type R

➤ Example:

Function<String, Integer> stringLength = s -> s.length();
System.out.println(stringLength.apply("Stanley")); // Output: 7

➤ Common Use Cases:

  • Transforming data in streams:
List<String> names = List.of("Stan", "Anna", "Leo");
List<Integer> lengths = names.stream()
                             .map(String::length)  // or .map(s -> s.length())
                             .toList();

DoubleFunction<R>

➤ Signature:

R apply(double value);

➤ Meaning:

  • Takes a double as input (primitive)
  • Returns a result of type R

➤ Why DoubleFunction exists?

Because Function<Double, R> would require autoboxing from double to Double, which is less performant. DoubleFunction<R> avoids that.

➤ Example:

DoubleFunction<String> describe = d -> "Weight: " + d + "kg";
System.out.println(describe.apply(73.5)); // Output: Weight: 73.5kg

✅ Summary Table

InterfaceInputOutputNotes
Function<T, R>T (any type)RMost general-purpose
DoubleFunction<R>doubleROptimized for primitives

There are also other similar primitive-specialized function interfaces:

InterfaceInputOutput
IntFunction<R>intR
LongFunction<R>longR
ToDoubleFunction<T>Tdouble
DoubleToIntFunctiondoubleint
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.