Java-8可选防止if语句

时间:2015-12-01 13:42:06

标签: java java-8 optional

有没有更好的方法:

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

2 个答案:

答案 0 :(得分:3)

如果您将DateTime变量的类型更改为Optional<DateTime>,则可以使用map来避免使用if语句:

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

其中“ClassName”应替换为firstScheduleRecordWeekCompendium的类型。

答案 1 :(得分:2)

由于您希望它保留默认值(null),如果没有值,您可以使用maporElse方法:

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