Nested functions in Java

Java 8 introduces lambdas.

java.util.function.BiConsumer<Integer, Integer> times = (i, num) -> {
    i *= num;
    System.out.println(i);
};
for (int i = 1; i < 100; i++) {
    times.accept(i, 2); //multiply i by 2 and print i
    times.accept(i, i); //square i and then print the result
}

The () -> syntax works on any interface that defines exactly one method. So you can use it with Runnable but it doesn’t work with List.

BiConsumer is one of many functional interfaces provided by java.util.function.

It’s worth noting that under the hood, this defines an anonymous class and instantiates it. times is a reference to the instance.

Leave a Comment