Cursor.hasNext throws java.util.NoSuchElementException

大憨熊 提交于 2020-01-22 02:25:28

问题


public String ForDate(String date) {
    MongoCursor<Document> cursor = collection.find(eq("date", date)).iterator();
    basicb b = new basicb();
    while (cursor.hasNext()) {
       b.setDepartament(cursor.next().getString("departament"));
       b.setText(cursor.next().getString("text"));
       b.setTitle(cursor.next().getString("title"));
       lista.add(b);
    }
}

I just want to do object from mongodb information but when I do this method get make some object but always return that errorjava.util.NoSuchElementException.


回答1:


Probably, the problem is that you are calling next method three times in a single loop. You should call it once and store its result in a variable, since next retrieves next element in the iteration

while (cursor.hasNext()) {
   Document element = cursor.next();
   b.setDepartament(element.getString("departament"));
   b.setText(element.getString("text"));
   b.setTitle(element.getString("title"));
   lista.add(b);
}


来源:https://stackoverflow.com/questions/42038978/cursor-hasnext-throws-java-util-nosuchelementexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!