It’s funny that I keep finding some simple utilities in core Java libraries that are not part of standard JDK after almost 15 years working with Java…
We are adding A LOT of functional APIs to GridGain 3.0 and many of the functional processing of collections works with Iterable interface. Yet – there’s no standard way to convert JDBC ResultSet to Iterable which is really just a few lines of code. Go figure why this was omitted…
The code below provides such conversation. Keep in mind that it is not 100% compatible with Iterator contract as you can’t call hasNext() more than once as it has side effect of advancing the result set. Other than that – you can use it with any functional constructs in GridGain 3.0 that require Iterable.
public static Iterable<ResultSet> asIterable(final ResultSet rs) {
return new Iterable<ResultSet>() {
@Override public Iterator<ResultSet> iterator() {
return new Iterator<ResultSet>() {
public boolean hasNext() {
try {
return rs.next();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
public ResultSet next() { return rs; }
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
Enjoy!