The following code return Nullpointer exception:
Comparator<LocalDate> c = (LocalDate d1,LocalDate d2)-> {return (d1.isAfter(d2) ? 1 : (d1.isBefore(d2)? -1: 0));} ;
List<LocalDate> list1 = new ArrayList<LocalDate>();
list1.add(null);
list1.add(null);
Optional<LocalDate> lastUsedDate = list1.stream()
.max(Comparator.nullsLast(c));
System.out.println(lastUsedDate.get());
Can someone please help me understand how this can be resolved ?
maxsays:throws NullPointerException if the maximum element is null. If you want to avoid that, you can filter out thenullelements from the stream, but in that case you won't need to useComparator.nullsLast().Stream::maxcan't handle that. That method returnsOptionalwhich can't represent null as a non-empty result. It also can't just return an empty optional because "empty" means "no value", yet there was a value: null. Hence the NPE.