Java Reference
In-Depth Information
In the last chapter, we started working with Funjava Result _type in order to capture the error
handling and make it an explicit part of the stream flow. We can take advantage of that result again. Instead
of our createStream method taking just a ResultSet, we will also require it to provide us an error handler.
Instead of registering the close with the Stream's onClose handler, we will perform the close immediately
in the processing flow. The caller will provide the implementation of error handling, and we will apply it
using the ResultErrorHandler class, just as we saw in the last chapter. The result is a much more robust
implementation of that method, and it is given in Listing 5-7.
Listing 5-7. Using the Result Type for a More Robust Stream.of and Stream.flatMap Conversion
public static Stream<WordUsage> createStream(
ResultSet resultSet, Consumer<Exception> errorHandler
throws SQLException {
return Stream.of(resultSet).flatMap(rs -> {
Stream.Builder<Result<WordUsage>> builder = Stream.builder();
try {
while ( {
try {
WordUsage usage = WordUsage.fromResultSet(rs);
} catch(SQLException sqle) {
} catch (SQLException sqle) {
} finally {
try {
} catch (SQLException sqle) {
).flatMap(new ResultErrorHandler<>(errorHandler));
Method Three: Building a Stream Using an AbstractSpliterator
In both of the previous cases, we built out the stream of results in memory, and then returned the entire
stream. This meant that we had to wait for all of the I/O to resolve before doing any processing, and we had
to store all the results in memory at the same time. If you have enough data to warrant an external database,
then those are probably not acceptable qualities in a solution. This solution, as well as the next, both offer an
alternative approach. These solutions will integrate the iteration of the result set into the stream processing
itself, meaning that the results can be processed piecemeal.
This solution will follow the more traditional Java approach: if you want to implement an interface, find
the abstract class which implements the interface, and build your implementation by extending that abstract
class. However, there is no AbstractStream to inherit from. Instead, we have to go a bit deeper. This is where
we meet the Spliterator.
Search WWH ::

Custom Search