This is the first of a series of blog posts that cover my journey of looking deeper into Java 8.
Note: The second post about streams has be published.
When working with Java you will sooner or later encounter anonymous classes (or various implementations of Runnable
and Comperator
) used to pass functionality as an argument to another method.
Both of the above are annotated as @FunctionalInterface
and can therefore be used (in Java 8) as the assignment target for a lambda expression or method reference.
This is a very common use case where you can take advantage of Java 8 lambdas.
Lambda expressions enable you to [...] treat functionality as method argument, or code as data. The Java™ Tutorials - Lambda Expressions
I took some time to come up with a dead simple hello world lambda with no arguments and no return value. My favorite solution in action:
Runnable helloWorld = () -> System.out.println("Hello, World!");
helloWorld.run();
There are various interesting new interfaces in the package java.util.function
.
The following examples use Supplier
, Consumer
and Function
.
We start with a simple Supplier
:
Supplier<Integer> fortyTwo = () -> 42;
System.out.println(fortyTwo.get()); // prints 42
Most probably you will encounter some method or constructor references over time.
A method reference (System.out::println
) might come as a java.util.function.Consumer
:
Consumer<String> printer = System.out::println;
printer.accept("Hello, World!");
a constructor reference (Integer::new
) as java.util.function.Function
:
Function<String, Integer> string2int = Integer::new;
int fourtyTwo = string2int.apply("42");
I hope you enjoyed this short intro to Java lambda expressions...