Explain Codes LogoExplain Codes Logo

How to get the first element of the List or Set?

java
collections
optional
error-handling
Nikita BarsukovbyNikita Barsukov·Aug 10, 2024
TLDR

Grab the first element from a List using .get(0):

// No one remembers who came to the party first, but a list does ;) String firstElement = new ArrayList<>(List.of("a", "b", "c")).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:

// Set's like: "First? Don't even talk about it." Set<String> set = new HashSet<>(Set.of("a", "b", "c")); String firstElement = set.isEmpty() ? null : set.iterator().next();

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:

// "Hello, any element out there?" if (!collection.isEmpty()) { // Safe to get the first element }

Embrace Optional for a more eloquent approach using .stream().findFirst():

// Feeling lucky? Let's see if we got an element... Optional<String> firstElement = list.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:
// Guava's like: "Let me handle this for you" String first = Iterables.getFirst(set, "default");
  • Apache Commons' IteratorUtils.get(iterator, index) is ready to take command:
// Apache commons: "Let's locate that first guy" String first = IteratorUtils.get(list.iterator(), 0);

Java 8+ Stream API perks

Java 8+'s Stream API has encouraged us to not just code, but stream our way through coding:

// Streams: "Look no further, I've got just the right element for you." listOrSet.stream().findFirst().ifPresent(element -> { // process the element });

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:

// Kotlin's like: "I've got my eyes on the first one!" val first = list.first()

For Java, let's not underestimate the power of polymorphism. It can be a one-size-fits-all solution with the Iterator:

// Our secret recipe to safely pick the first element public static <T> T safeFirst(Collection<T> coll, T defaultValue) { return coll != null && !coll.isEmpty() ? coll.iterator().next() : defaultValue; }

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 the next() method.