|
The java.util.function.Function<T, R> interface defines an abstract method named
apply, which takes an object of generic type T as input and returns an object of generic type
R. You might use this interface when you need to define a lambda that can extract information
from the input object (for example, extracting the weight of an apple) or transform the input
(for example, a string to its length). In the code that follows we show how you can use it to
create a method map to transform a list of String into a list of Integer containing the length
of each String:
public interface Function<T, R>{
public R apply(T t);
}
public static <T, R> List<R> map(List<T> list,
Function<T, R> f) {
List<R> result = new ArrayList<>();
for(T s: list){
result.add(f.apply(s));
}
return result;
}
// [7, 2, 6]
List<String> l = map(
Arrays.asList("lambdas","in","action"),
(String s) -> s.length() #A
);
#A: The lambda is the implementation for the apply method of Function
PRIMITIVE SPECIALIZATIONS
We described three functional interfaces that are generic: Predicate<T>, Consumer<T>, and
Function<T, R>. There are also functional interfaces that are specialized with certain types.
To refresh a little: every Java type is either a reference type (for example, Byte, Integer,
Object, List) or a primitive type (for example, int, double, byte, char). But generic
parameters (for example the T in Consumer<T>) can only be bound to reference types. This is
due to how generics are internally implemented. Some other languages such as C# don’t have
this restriction. Other languages such as Scala only have reference types. As a result, in Java
there’s a mechanism to convert a primitive type into a corresponding reference type. This
mechanism is called boxing. The dual (that is, converting a reference type into a
corresponding primitive type) is called unboxing. Java has also a mechanism called autoboxing
to facilitate the task for programmers: boxing and unboxing operations are done
automatically. |
|