Most efficient way to get the last element of a stream

Bohemian picture Bohemian · Dec 18, 2014 · Viewed 47.5k times · Source

Stream doesn't have a last() method:

Stream<T> stream;
T last = stream.last(); // No such method

What's the most elegant and/or efficient way to get the last element (or null for an empty Stream)?

Answer

Bohemian picture Bohemian · Dec 18, 2014

Do a reduction that simply returns the current value:

Stream<T> stream;
T last = stream.reduce((a, b) -> b).orElse(null);