Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ch.claude_martin;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Spliterator;
- import java.util.Spliterators;
- import java.util.function.Consumer;
- import java.util.stream.Stream;
- import java.util.stream.StreamSupport;
- class SomeClass {
- public static void main(String[] args) throws Throwable {
- Connection conn = null;
- PreparedStatement stmt = conn.prepareStatement("SELECT * FROM FOO", ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet rs = stmt.executeQuery();
- long size;
- try {
- rs.last();
- size = rs.getRow();
- rs.beforeFirst();
- } catch (Exception ex) {
- size = Long.MAX_VALUE;
- }
- Stream<Foo> stream = StreamSupport.stream(new AbstractSpliteratorExtension(rs, size), false);
- var result = stream.map(mapper1).map(mapper2).filter(someFilter).collect(myCollector);
- }
- private static final class AbstractSpliteratorExtension extends Spliterators.AbstractSpliterator<Foo> {
- private final ResultSet rs;
- private AbstractSpliteratorExtension(ResultSet rs, long size) {
- super(size, Spliterator.ORDERED);
- this.rs = rs;
- }
- @Override
- public boolean tryAdvance(Consumer<? super Foo> action) {
- try {
- if (!rs.next())
- return false;
- action.accept(Foo.of(rs));
- return true;
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
- }
- public static class Foo {
- public static Foo of(ResultSet rs) { ... }
- }
- }
Add Comment
Please, Sign In to add comment