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
Interface | Input | Output | Notes |
---|---|---|---|
Function<T, R> | T (any type) | R | Most general-purpose |
DoubleFunction<R> | double | R | Optimized for primitives |
There are also other similar primitive-specialized function interfaces:
Interface | Input | Output |
---|---|---|
IntFunction<R> | int | R |
LongFunction<R> | long | R |
ToDoubleFunction<T> | T | double |
DoubleToIntFunction | double | int |