Java Reference
In-Depth Information
With this iterator, it is now the user's responsibility to know what characteristics to pass in when creating
the spliterator. We saw from the last section that we can pass in DISTINCT, IMMUTABLE, and NONNULL.
Once we create that spliterator, we will pass it into the just like last time. This code is
in Listing 5-14.
Listing 5-14. Creating a Stream from a ResultSetIterator
public static Stream<WordUsage> createStream(
Connection conn, ResultSet resultSet
) throws SQLException {
Iterator<WordUsage> usages =
new ResultSetIterator<WordUsage>(resultSet, conn) {
protected WordUsage processRow(final ResultSet resultSet)
throws SQLException
return WordUsage.fromResultSet(resultSet);
Spliterator<WordUsage> spliterator =
Spliterator.NONNULL | Spliterator.DISTINCT | Spliterator.IMMUTABLE
Stream<WordUsage> stream =, true);
return stream;
In this case, this final solution is just as fast as the solution before. From an API standpoint, we have
moved the responsibility for understanding and deciding the characteristics to the user, and we have forced
him to make the call to Spliterators.spliteratorUnknownSize . Those are both less than optimal, but they
are hardly onerous. Given the situation, this is the solution that I would go with in my code. But it won't work
in all situations.
Specifically, you will want to implement your own spliterator if you can be very efficient with
the splits. If you can split your work load in an intelligent and efficient way, then providing your own
implementation for Spliterator.trySplit is a huge win. A ResultSet — and any other kind of
single-stream processing, like any — does not really give you much to work with. But if
you do encounter a situation where you can be smart about trySplit , then certainly implement your
own Spliterator .
Pulling It All Together
We are finally ready to pull it all together: the stream and all its various parts. We will use the
ResultSetSpliterator implementation, since we have it and it has the nicest user API. We will then map
that into tab-separated values using the WordUsage.toTSV() method. Finally, we will print the tab-separated
values as a String out to our standard out. The code for this is given in Listing 5-15.
Search WWH ::

Custom Search