java8-正确使用Optional

240 阅读1分钟

构造方法

Optional的有参和无参构造函数都是私有的,通过静态方法创造实例
1、empty()
2、of(T value) value不能为null
3、ofNullable(T value)

不推荐使用的方法

1、isPresent(),通过这种方式判断对象是否存在和null != value没有区别
2、get(),会抛出异常,使用前需要调用isPresent()判断是否为null

正确的打开方式

orElse或者orElseGet 获取对象

Optional<User> userOpt = Optional.ofNullable(null);

System.out.println(userOpt.orElse(null));
System.out.println(userOpt.orElseGet(() -> new User("Unknown", 999)));

ifPresent 方法进行对象操作

User user = new User("Tom", 21);
Optional<User> userOpt = Optional.ofNullable(user);

userOpt.ifPresent(u -> u.setAge(999));
System.out.println(user.getAge());

map或者flatMap 获取对象的数据