0

I am reading MongoDB results using the following code , however the while loop runs in an infinite loop always iterating over the first element in the collection, can someone point out what I am doing wrong.

       Iterable<DBObject> list = playerData.results();
        if(list != null){
            while(list.iterator().hasNext()) {

                DBObject obj = list.iterator().next();
                DBObject id =  (DBObject) obj.get("_id");
                String player= obj.get("player").toString();
                //Populate the memcached here .
                PlayerDTO rcd = new PlayerDTO();

                if(id != null && id.get("venue" != null && id.get("score") != null) {

                    rcd.setVenue(id.get("venue").toString());
                    rcd.setScore(new Double(id.get("score").toString()).doubleValue());
                }

            }
        }

1 Answer 1

2

You are reassigning the original iterator to the while() loop each iteration through.

Iterator i = list.iterator();
while(i.hasNext()) {
  ....
}
Sign up to request clarification or add additional context in comments.

4 Comments

Or a nicer for ( DBObject obj : list ) { do_stuff_with_obj }
indeed. that is the cleaner way.
Thanks, but I am surpised to know that list.iterator() returns a new iterator everytime!
Why? I think it's pretty obvious. What if you want to iterate twice?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.