Java Reference
In-Depth Information
Listing 5-15. Query with Mapping and Printing Out
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.*;
public class Listing15 {
public static void main(String[] args) throws Exception {
Database.createDatabase();
Connection conn = Database.getConnection();
Stream<WordUsage> stream = createStream(conn, Database.queryResults(conn));
stream.map(WordUsage::toTSV).forEach(System.out::println);
}
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;
}
}
That is a lot of power for a very little bit of code. It is also extremely extensible, and it is very clear where
the process steps fit into the workflow, and what is workflow and what is the implementation of steps.
This is an excellent example of the powerfully expressive postfunctional coding style of Java 8, even when
having to interact with ugly and difficult legacy code.
 
Search WWH ::




Custom Search