Java Reference
In-Depth Information
Lambdas with No Return Value
So far, we have been addressing lambdas that always return a value. A very common type of lambda,
however, returns no value at all: these are terminal lambdas. You see them, for instance, when consuming
every element of a collection or when terminating a stream of values. They are the opposite of suppliers;
they take a value and produce nothing as a result. Predictably, the functional interface for these consuming
lambdas is Consumer . An example of a consumer is given in Listing 2-13: there, we use a consumer to
represent how we print out the greeting. A more idiomatic Java 8 way of writing this code will be given when
we get to collections in Chapter 3.
Listing 2-13. Example of a Consumer and BiConsumer
public static void greetFolks() {
Consumer<String> doGreet = name -> System.out.println("Hello, " + name);
for (String name : Arrays.asList("Alice", "Bob", "Cathy")) {
public static void concat() {
BiConsumer<String,String> printConcat = (left,right) ->
System.out.println(left + right);
for (String name : Arrays.asList("Alice", "Bob", "Cathy")) {
printConcat.accept("Goodbye, ", name);
Lambdas with Complex Bodies
Usually, lambdas are simple, single-element affairs. Occasionally, however, you need to do something a bit
more involved. This is especially common when you are writing code that interfaces with a pre-lambda API,
such as working with an Autocloseable . If you need to create a complex body on a lambda, you can specify
the body within brackets. When you do so, however, you take on responsibility for explicitly calling a return .
An example of a lambda wrapping an Autocloseable is given in Listing 2-14. As you can see there, this
approach makes your lambda look a lot more like a method, and you may be better off defining a method
and referring to it explicitly. There's even a nice syntax for turning a method back into a lambda if you need
to: see “Making Methods into Lambdas” below.
Listing 2-14. Lambda with a Complex Body That Wraps an Autocloseable
Function<File, Byte> firstByte = file -> {
try (InputStream is = new FileInputStream(file)) {
return (byte);
} catch (IOException ioe) {
throw new RuntimeException("Could not read " + file, ioe);
for (String filename : args) {
File file = new File(filename);
int byte1 = firstByte.apply(file);
System.out.println(filename + "\t=>\t" + byte1);
Search WWH ::

Custom Search