I\'ve got a class that implements Iterator with a ResultSet as a data member. Essentially the class looks like this:
public class A implements Iterator{
Here's my iterator that wraps a ResultSet. The rows are returned in the form a Map. I hope you'll find it helpful. The strategy is that I always bring one element in advance.
public class ResultSetIterator implements Iterator> { private ResultSet result; private ResultSetMetaData meta; private boolean hasNext; public ResultSetIterator( ResultSet result ) throws SQLException { this.result = result; meta = result.getMetaData(); hasNext = result.next(); } @Override public boolean hasNext() { return hasNext; } @Override public Map next() { if (! hasNext) { throw new NoSuchElementException(); } try { Map next = new LinkedHashMap<>(); for (int i = 1; i <= meta.getColumnCount(); i++) { String column = meta.getColumnName(i); Object value = result.getObject(i); next.put(column,value); } hasNext = result.next(); return next; } catch (SQLException ex) { throw new RuntimeException(ex); } } }