Functional Interfaces: Function

Mutates and returns an existing object, or maps an existing object to a new one.

Overview

Example

Map 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?)