Most efficient way to get the last element of a stream

java, java-8, java-stream

Solution

Do a reduction that simply returns the current value:

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

Problem

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)?

Original source