NoSuchElementException
JavaERRORCommonCollection
No element available in iterator or Optional
Quick Answer
Check hasNext() before next(), or use Optional.orElse() instead of Optional.get().
What this means
Thrown by Iterator.next(), Scanner methods, or Optional.get() when no element is available.
Why it happens
- 1Calling Iterator.next() without checking hasNext()
- 2Optional.get() on an empty Optional
Fix
Use orElse / orElseThrow instead of get
Use orElse / orElseThrow instead of get
String val = opt.orElse("default");
String val2 = opt.orElseThrow(
() -> new IllegalStateException("value required"));Why this works
orElseThrow gives a more descriptive error than NoSuchElementException from get().
Code examples
Triggerjava
Optional.empty().get(); // NoSuchElementException
Safe Optionaljava
String result = findUser(id)
.map(User::getName)
.orElse("unknown");Stream findFirstjava
list.stream()
.filter(s -> s.startsWith("A"))
.findFirst()
.orElseThrow(() -> new NotFoundException("no match"));Same error in other languages
Sources
Official documentation ↗
Java SE Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev