Introduction
In this short tutorial, we'll explain how the Function interface is used and present a sample code where we're converting a list of string values into a list of integers that represent the length of strings from the input list.
The Function interface was introduced in Java 8 and is part of the java.util.function package. This functional interface can be used as the assignment target for a lambda expression or method reference. It represents a function that takes in one argument and produces a result. Input and output do not have to be of the same type. Interface definition requires two generic type parameters:
-
T: represents the type of the input argument
-
R: represents the return type of the function
Example
Let's see in the example how to define the Function and how to use it in code.
public class FunctionExample {
public static void main(String[] args) {
List<String> listOfStringElements = List.of("First", "Second", "Third");
Function<String, Integer> function = String :: length;
List<Integer> listOfStringLenghts = map(listOfStringElements, function);
System.out.println(listOfStringLenghts);
}
private static <T, R> List<R> map(List<T> list, Function<T, R> function) {
List<R> newList = new ArrayList<>();
list.stream().forEach((e)->newList.add(function.apply(e)));
return newList;
}
}
Conclusion
In this article, we presented the Java Function interface and explained how to use Function to convert a list of Strings to a list of integers representing the length of input Strings. More documentation on Function could be found in the Oracle official documentation.