欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Optional

程序员文章站 2022-03-04 11:35:17
...

记录下test

(Optional.ofNullable)

Optional.ofNullable(user):user可为空也可非空
Optional.of(user):user不可为空,空报npe

(Optional.ofNullable.orElse)

@Data
public class UserModel {
    private Integer id;
    private String name;
    private Date date;
    private int age;

    public UserModel(Integer id, String name, Date date, int age) {
        this.id = id;
        this.name = name;
        this.date = date;
        this.age = age;
    }
}
 @Test
    public void givenEmpty() {
        UserModel user = new UserModel(2, "x", new Date(), 23);
        log.debug("Using orElse");
        UserModel result = Optional.ofNullable(user).orElse(createNewUser());
        System.err.println(JSON.toJSONString(result));
        log.debug("Using orElseGet");
        UserModel result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
    }

    private UserModel createNewUser() {
        System.err.println("Creating New User");
        return new UserModel(1, "extra", new Date(), 12);
    }

当user为空时
输出为见下面:orElse()和orElseGet一样

16:26:27.705 [main] DEBUG com.example.demo.lambda.StreamTest - Using orElse
Creating New User
{"age":12,"date":1562833587707,"id":1,"name":"extra"}
16:26:27.796 [main] DEBUG com.example.demo.lambda.StreamTest - Using orElseGet
Creating New User

但是当user不为空时
输出为见下面:可以看到orElse()后面的语句依然会执行,但是orElseGet()不会执行,所以日常推荐使用orElseGet(),提升性能

16:23:35.197 [main] DEBUG com.example.demo.lambda.StreamTest - Using orElse
Creating New User
{"age":23,"date":1562833415196,"id":2,"name":"x"}
16:23:35.318 [main] DEBUG com.example.demo.lambda.StreamTest - Using orElseGet

Optional.ofNullable.map