Java8 新特性Optional

1,前提

最近看项目代码,发现好多地方都使用到了Optional,所以在此记录一下,后面Optional使用还会持续更新此文章。。。。

2,代码


import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;


IPage<Student> page= studentServiceImpl.listPage();
Optional.ofNullable(page).map(IPage::getRecords).orElse(Lists.emptyList()).forEach(Student::refreshAge);


public class Student extends BaseModel {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private LocalDate birthday;
  
    private Integer age= 0;
    
    public void refreshAge(){
        if(this.birthday != null){        
            this.age= (int)(LocalDate.now().toEpochDay()-this.birthday.toEpochDay());
        }
    }
}

好文推荐

JAVA8 - Optional中map、orElse、orElseGet是否执行
Java8新特性 - Optional 全解

你可能感兴趣的:(Java,java)