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 […]
