Java – call stream() Reduce () in the list has only one element
I am a new function programmer of Java and want to know how I should write code to avoid NPE (for example):
myList.stream() .reduce((prev,curr) -> prev.getTimestamp().isAfter(curr.getTimestamp()) ? prev : curr); .get().getTimestamp();
My intention is to find the timestamp of the latest object in the list Suggestions on how to better collect the last element are very welcome, but my main question is actually why it works
The document says that the function will throw a NullPointerException "if the restored result is empty":
http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce -java. util. function. BinaryOperator-
This is OK, but I don't quite understand why I won't get NullPointerException when the code runs with only one element list In this case, I expect prev to be null I try debugging, but when there is only one element, it just seems to span the entire lambda expression
Solution
As stated in the Javadoc of reduce, reduce is equivalent to:
boolean foundAny = false; T result = null; for (T element : this stream) { if (!foundAny) { foundAny = true; result = element; } else result = accumulator.apply(result,element); } return foundAny ? Optional.of(result) : Optional.empty();
Therefore, if the stream has a single element, the loop has only one iteration and returns the single element found in that iteration
Binaryoperator is applied only if the stream has at least two elements