0
Date finalexamDate = Person.stream()
    .map(PersonDetails::getexamDate)
    .max(Date::compareTo)
    .orElse(null);

The following code produces a

null pointer exception

as this person doesnt have any getexamdate during this case I wanted to return null to the finalexamDate

Tried adding Optional.ofNullable still produces the same error.

How should this be handled ? is there any way to handle along with the same line of code rather than checking one more if condition ?

user207421
  • 305,947
  • 44
  • 307
  • 483
A K
  • 25
  • 6

1 Answers1

1

The max terminal method throws a Null pointer Exception if the maximum value is null . So it is safe to filter the values first so that the stream will only have non null values in it.

Date finalexamDate = Person.stream()
    .map(PersonDetails::getexamDate)
    .filter(Objects::nonNull)
    .max(Date::compareTo)
    .orElse("some default value");
Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39