FunctionMutates and returns an existing object, or maps an existing object to a new one.
Used to map a value of one type to a value of another, or to mutate an object in-place (returning the mutated object rather than a new object).
Often employed to transform all of the items in a Stream, using Stream.map(Function).
Parameterized by the type of the original value (T) and the type of the mapped value (R); these may, in fact, be the same type (UnaryOperator<T> extends Function<T,R> explicitly for this purpose). If used in Stream.map(Function), then this also has the effect of changing a Stream<T> (upstream from the map(Function<T,R>) operation) to a Stream<R> (downstream from the map(Function<T,R>) operation).
Method to be implemented is R apply(T t). Thus, a lambda implementation must take a single parameter of type T, and return a value of type R.
Stream of random values to dice rolls using Stream.map(Function):Stream.generate(Math::random) // Stream of values in [0, 1).
.limit(100) // Take only the first 100 values.
.map((v) -> 1 + (int) (6 * v)) // Map from [0, 1) to {1 … 6}.
.forEach(System.out::println); // Print each value.
The example uses a lambda implementing Supplier<Double> to generate a Stream<Double> of pseudo-random numbers. Then, a lambda implementation of Stream.map(Function) is used to map the Double values to Integer values in the range from 1 to 6 (inclusive)—i.e. random dice roll values. (Note that this example includes 2 auto-boxing operations, and 1 auto-unboxing operation. Can you spot them?)