Java Reference
In-Depth Information
// Perform the stream processing
Function<Integer, Optional<Integer>> mapFunction =;
// Work with the exceptions
Map<Object, Exception> exceptions = handler.getExceptions();
exceptions.forEach((key, val) -> {
System.out.println(key + ": " + val);
This approach, however, requires that we have the extra handling in place to extract the values from
within their Optional container. There is another alternative based on flatMap , which we first saw back in
chapter 3: we could have our values return a stream, and the stream can be empty or it can be populated
with a single element. This allows us to sidestep the Optional type and its extraction, although it hides any
symptom of the error from the stream itself. Still, the API is overall a bit nicer, even if you have to call the
flatMap method to perform what is effectively a simple map operation. This code is given in Listing 7-5.
Listing 7-5. Handling Resources with an Object Using flatMap
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
public class Listing5 {
public static class ResourceExceptionHandler
<RESOURCE_T extends AutoCloseable>
public static interface FunctionWithResource
<RESOURCE_T extends AutoCloseable, IN_T, OUT_T>
OUT_T apply(RESOURCE_T resource, IN_T value) throws Exception;
public static interface ResourceMaker<RESOURCE_T extends AutoCloseable> {
RESOURCE_T create() throws Exception;
Search WWH ::

Custom Search