I am new to functional programming in java, and wonder how I should code to avoid NPE in (for example) this operation:
myList.stream()
.reduce((prev, curr) -> prev.getTimestamp().isAfter(curr.getTimestamp()) ? prev : curr);
.get().getTimestamp();
My intent here is to find the timestamp of the newest object in the list. Suggestions on how to better collect the last element are very welcome, but my main question here is actually why this works.
The documentation says that the function throws a NullPointerException
"if the result of the reduction is null":
That is OK, but what I don't quite understand is why I don't get a NullPointerException
when this code is run with a list containing only one element. I expected prev
to be null in such a case. I tried debugging, but it just seems to step over the entire lambda expression when there is only one element.