Java Code Example: function

In this example, we define a lambda expression (n) -> "Number: " + n and assign it to a Function<Integer, String> functional interface. The lambda expression takes an Integer argument and returns a String by concatenating the argument with the “Number: ” prefix.

We then use the apply method on the convertToString object to apply the lambda expression to the number 42, which returns the string “Number: 42”. Finally, we print the result string, which outputs “Number: 42” to the console.

The Function functional interface is widely used for transforming data from one type to another. It takes an input of type T and produces an output of type R. In this example, it takes an Integer and returns a String.

import java.util.function.Function;

Function<Integer, String> convertToString = (n) -> "Number: " + n;
String result = convertToString.apply(61);
System.out.println(result);
Output
Number: 61