How to get the first element of the List or Set?
Grab the first element from a List
using .get(0)
:
For a Set
, the .iterator().next()
approach works, but always remember to check if it's empty as a courtesy to avoid exceptions:
Guarding against empty collections
Usain Bolt wouldn't start the race without opponents, neither should your code while fetching the first element
. Always check if the collection is non-empty:
Embrace Optional
for a more eloquent approach using .stream().findFirst()
:
Power of third-party libraries: Guava and Apache Commons
For a robust solution, consider third-party veterans like Guava or Apache Commons:
- Guava's
Iterables.getFirst(collection, defaultValue)
can be your lifesaver:
- Apache Commons'
IteratorUtils.get(iterator, index)
is ready to take command:
Java 8+ Stream API perks
Java 8+'s Stream API has encouraged us to not just code, but stream our way through coding:
In this snippet, findFirst()
graciously hands over the Optional
object representing the first hero of our collection.
Kotlin syntax and the versatile approach
In Kotlin, the first()
function does exactly what it says:
For Java, let's not underestimate the power of polymorphism. It can be a one-size-fits-all solution with the Iterator
:
This handy method ensures you get the first element or a default value if the collection is empty, safely parking NoSuchElementException
out of the equation.
Error handling and safety run hand-in-hand
While retrieving the first item, remember these golden rules of error handling:
- Be a good host; add a welcome mat of null checks or isEmpty() checks before you welcome your guests (elements).
- Use Optional or defaultValue as your bodyguards to safeguard against potentially empty collections.
- Don't ignore the
UnsupportedOperationException
, an unwelcomed guest that can crash the party if your collection's iterator doesn't bring along thenext()
method.
Was this article helpful?