Java Reference
In-Depth Information
Listing 5-12. Generating a New Stream Using ResultSetSpliterator
public static Stream<WordUsage> createStream(
Connection conn, ResultSet resultSet
) throws SQLException {
Spliterator<WordUsage> usages =
new ResultSetSpliterator<WordUsage>(
resultSet, Spliterator.DISTINCT, conn
) {
@Override
protected WordUsage processRow(final ResultSet resultSet)
throws SQLException
{
return WordUsage.fromResultSet(resultSet);
}
};
Stream<WordUsage> stream = StreamSupport.stream(usages, true);
return stream;
}
Method Four: Building a Stream from an Iterator
Although building out a spliterator was very educational, it was also a lot of work. If you do not need that
level of control, you can build a spliterator from an iterator, and then build a stream from there. There are
two bridge methods that get from an Iterator to a Spliterator: Spliterators.spliterator (Iterator,
long, int) and Spliterators.spliteratorUnknownSize (Iterator, int) . The former is used when you
know the size of the elements that will be iterated over; the latter is for when you do not know the size. The
former is notably more efficient than the latter, so if you can figure out the size ahead of time, definitely use
it. In both cases, you pass the characteristics of the spliterator as the final argument.
Building an iterator for a ResultSet is notably simpler than building a spliterator. Our iterator
implementation is therefore a simplification of our spliterator implementation in Listing 5-11. The only catch
is that the single tryAdvance method of the Spliterator is two distinct methods in the Iterator class: hasNext()
and then next() . Because of this, we will need to be able to store some state about whether or not there is a
next element. This is a ternary variable: it can either be true, false, or unknown. This is one of the few legitimate
uses of null : by using the Boolean type, we can get those three states. The implementation of our iterator is
given in Listing 5-13.
Listing 5-13. ResultSetIterator Implementation
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* An {@link java.util.Iterator} that traverses a {@link java.sql.ResultSet}.
* When the result set is exhausted,
* it will be automatically closed. Implementing classes should extend
* {@link #processRow(java.sql.ResultSet)} to
* specify how to convert a row into a result object.
 
Search WWH ::




Custom Search