[JAVA-29] facilitate use of "for (X x : collection)" syntax with DBCursor Created: 02/Sep/09  Updated: 02/Oct/09  Resolved: 04/Sep/09

Status: Closed
Project: Java Driver
Component/s: None
Affects Version/s: None
Fix Version/s: 0.9

Type: Improvement Priority: Minor - P4
Reporter: Jason Sachs Assignee: Eliot Horowitz (Inactive)
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Just some food for thought. DBCursor implements Iterator<DBObject> but not Iterable<DBObject> so cannot directly be used in a for loop. Consider implementing Iterable<DBObject> as well, and add its one method perhaps as follows:

@Override public Iterator<DBObject> iterator() {
return this.copy();
// outgoing copy() might not be necessary (you could just "return this;") but just to be safe
}

This allows the syntax

DBCursor cursor = db.find(query);
for (DBObject object : cursor)
{
// do something with "object"
}

or even

for (DBObject object : db.find(query))
{
// do something with "object"
}

It's only a minor convenience over

DBCursor cursor = db.find(query);
while (cursor.hasNext())
{
DBObject object = cursor.next();
// do something with "object"
}

but makes loop code just a bit more clear.

I'm getting around this by making my own wrapper class:
static public class CursorWrapper implements Iterable<DBObject>
{
private final DBCursor cursor;
private CursorWrapper(DBCursor cursor)

{ this.cursor = cursor; }

static public CursorWrapper wrap(DBCursor cursor)

{ return new CursorWrapper(cursor.copy()); // incoming copy() might not be necessary, but just to be safe }

@Override public Iterator<DBObject> iterator()

{ return this.cursor.copy(); // outgoing copy() might not be necessary, but just to be safe }


}

and then can do

for (DBObject obj : CursorWrapper.wrap(coll.find().limit(100)))

{ System.out.println(obj.get("metadata")); }
Generated at Thu Feb 08 08:51:21 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.