June 2017
Intermediate to advanced
400 pages
8h 44m
English
Consumer<T> accepts a T argument and performs an action with it but does not return any value. Using an anonymous class, we can create a Consumer<String> that simply prints the string as shown in the following code snippet:
import java.util.function.Consumer;public class Launcher { public static void main(String[] args) { Consumer<String> printConsumer = new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } }; printConsumer.accept("Hello World"); }}
The output is as follows:
Hello World
You can implement this as a lambda. We can choose to call the String parameter s on the left-hand side of the lambda arrow -> and print it on the right-hand side:
import java.util.function. ...
Read now
Unlock full access