quma
quma

Reputation: 5733

Java-8 Optional prevent if statement

Is there a better way of doing this:

DateTime firstRecordingDate = null;
if (firstScheduleRecordWeekCompendium.isPresent()) {
    firstRecordingDate = firstScheduleRecordWeekCompendium.get().getStartRecord();
}
DateTime lastRecordingDate = null;
if (firstScheduleRecordWeekCompendium.isPresent()) {
    lastRecordingDate = firstScheduleRecordWeekCompendium.get().getStartRecord();
}

Upvotes: 3

Views: 107

Answers (2)

flo
flo

Reputation: 10241

Since you want it to stay with a default value (null) if no value is present, you can use the map and orElse methods:

DateTime firstRecordingDate = firstScheduleRecordWeekCompendium
    .map(YourClass::getStartRecord)
    .orElse(null);

Upvotes: 2

Eran
Eran

Reputation: 393771

If you change the type of your DateTime variables to Optional<DateTime>, you can avoid the if statement using map :

Optional<DateTime> firstRecordingDate = firstScheduleRecordWeekCompendium.map(ClassName::getStartRecord);

Where "ClassName" should be replaced with the type of firstScheduleRecordWeekCompendium.

Upvotes: 3

Related Questions