NoSuchElementException from Iterator

java.util.NoSuchElementException

Quick Answer

You called next() on an iterator that has no more elements. Always check hasNext() before calling next().

Why This Happens

Iterator.next() throws NoSuchElementException when there are no more elements. This happens when you call next() without checking hasNext() first, or when you call next() more times than there are elements in the collection.

The Problem

List<String> list = new ArrayList<>();
Iterator<String> it = list.iterator();
String first = it.next(); // NoSuchElementException on empty list

The Fix

List<String> list = new ArrayList<>();
Iterator<String> it = list.iterator();
if (it.hasNext()) {
    String first = it.next();
}

Step-by-Step Fix

  1. 1

    Identify the next() call

    Find the Iterator.next() or Scanner.next() call that fails in the stack trace.

  2. 2

    Check why there are no elements

    Verify that the collection or input source actually contains elements at the point where next() is called.

  3. 3

    Guard with hasNext()

    Always call hasNext() before next(), or use for-each loops which handle this automatically.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free