The simplest way is something like the following:
stream.reduce((a, b) -> b)
.orElseThrow(() -> new IllegalStateException("no last element"));
Note that this form of reduce() returns an Optional, which forces you to decide what to do if there are no elements in the stream. (This is a good thing.) The above example throws an exception if the stream is empty. An alternative is to have it use a default value instead:
stream.reduce((a, b) -> b)
.orElse(default_value);
Leave a Reply