Explain Codes LogoExplain Codes Logo

Get last element of Stream/List in a one-liner

java
reduce
performance
best-practices
Anton ShumikhinbyAnton Shumikhin·Feb 8, 2025
TLDR

To get the last element of a List by converting it to a Stream and using reduce((a, b) -> b):

Optional<T> lastElement = list.stream().reduce((a, b) -> b);

This code conveniently wraps the last element in an Optional<T> to avoid NullPointerExceptions when dealing with empty lists.

And if you are a Google Guava user:

T lastElement = Iterables.getLast(list, defaultValue); // Ahoy! I'm your safety net when the list is empty.

Precautions with infinite streams

If your stream is a never-ending party, trying to get the last guest isn't going to end well. Always check your Stream party has a definitive end time, else, you'll be stuck getting the last party-goer forever.

Priority: Performance vs simplicity

The simplicity of reduce() is enticing, but beware—it might fancy a slow dance, given its linear time complexity. For larger guest lists or when performance is top-priority, Streams.findLast() by Google Guava should be your +1 — it's a quicker dancer with logarithmic to linear time complexity.

Addressing void: Handling empty lists

Uh oh, your guest list was empty, and you didn't know until you tried greeting the last arrival. To avoid embarrassment — or, rather, NoSuchElementException — always check for party-goers before trying to find the last guest:

Optional<T> lastGuest = list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1)); // Are we expecting anyone tonight?

Zen of Reduction

Working with reduce()? Make sure the accumulator function is stateless and associative to avoid any dance-offs - inaccurate results or slower performance, especially when your conga line moves in parallel.

Order of the conga line: Ordered vs unordered streams

When using reduce(), the sequence of the conga line matters; for ordered streams, you'll find the last dancer, but if the line is unordered, it's anyone's game — this is findAny() in disguise!

For the experts: Special Tips

Custom Dance: Custom Collecting

Want to choreograph your own dance routine? You can create a custom Collector to define your moves for finding the last dancer. May seem over-the-top, but hey, going the extra mile often pays off in learning.

Stay in Rhythm: Avoid Expensive Operations

Don't try to rearrange the entire conga line just to find the last dancer— you'll exhaust everyone! Sorting the whole stream is a big no-no.

If it's a Queue or Deque

When working with a Queue or Deque, use their built-in methods like peek() or getLast(). These dancers know their routines well - they get you the last element really quick!

T lastElement = aDeque.getLast(); // Last one standing!