Java Reference
In-Depth Information
Then the flattened list contains all the elements of those inner lists, but without the inner list structure.
It would look like this:
List<String> flatList = Arrays.asList(
"Eddard Stark", "Catelyn Tully", "Benjen Stark",
"Lysa Telly", "Jon Arryn", "Robin Arryn",
"Cersei Lannister", "Robert Baratheon"
);
The flatMap method allows you to perform a corresponding operation on a Stream . This is the API:
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
You can pass in a function that takes an element of the stream and returns a new Stream of any type.
All those returned streams are concatenated together and processed. This is how we will concatenate the
results together for the files that we read, which is what the API is really designed for. However, it can also be
used when you have an optional return value from a mapping operation. To do this, we will return Stream.
empty() when there is no result, and Stream.of(element) when we have a result. Here is the resulting class:
Listing 4-7. Result Mapping Function
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
/**
* A class intended to be passed to
* {@link Stream#flatMap(java.util.function.Function)} to process
* {@link Result} instances. The class is constructed with an exception handler
* that will be passed any exceptions, and the {@link #apply(Result)} method
* will return a stream containing the result (if any). The stream has 0
* elements if the {@link Result} instance had no result, and has 1 element if
* the instance had a result.
*/
public class ResultMap<RESULT_T>
implements Function<Result<RESULT_T>, Stream<RESULT_T>>
{
private final Consumer<Exception> exceptionHandler;
/**
* Constructs an instance that will delegate to the given exception handler.
*
* @param exceptionHandler The handler for exceptions in the stream; never
* {@code null}
*/
Search WWH ::




Custom Search