public class User {
private Long id;
private String name;// 身份证对象
private IdCard idCard;// getter、setter、toString
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
身份证类:
public class IdCard {
private Long id;// 身份证号码
private String idNum;// getter、setter、toString
}
1.
2.
3.
4.
5.
6.
测试类:获取用户的身份证号码
public class OptionalMain {
public static void main(String[] args){// 创建用户对象
User user = new User();// 调用一系列get方法获取身份证号码
// 因为调用 getIdCard()时并没有身份证对象为null,再调用getIdNum方法则出现 NullPointerException
String idNum = user.getIdCard().getIdNum();
System.out.println(idNum);}}
/** * A container object which may or may not contain a non-null value. 一个可以包含或不包含非空值的容器对象 * If a value is present, {@code isPresent()} will return {@code true} and * {@code get()} will return the value. 如果存在值,isPresent()方法会返回true,通过get()方法返回值 * * <p>Additional methods that depend on the presence or absence of a contained * value are provided, such as {@link #orElse(java.lang.Object) orElse()} * (return a default value if value not present) and * {@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block * of code if the value is present). 提供了取决于是否存在包含值的其他方法,比如orElse,如果值不存在,则返回默认值 并且 可以通过ifPresent() 判断值是否存在,存在则执行代码块 * <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a> * class; use of identity-sensitive operations (including reference equality * ({@code ==}), identity hash code, or synchronization) on instances of * {@code Optional} may have unpredictable results and should be avoided. 这是一个基于值的类,应避免使用于身份敏感操作【这里应该意思是:对象是否存在不确定的敏感操作】(包括引用 ==,哈希或同步)的实例可能会产生不可预测的结果 * @since
User user = new User(1L,"格雷福斯");
Optional<User> userOptional = Optional.ofNullable(user);// 为null直接返回`Supplier`生产型函数接口返回的对象
String name = userOptional.orElseGet(() new User(0L,"添甄")).getName();
System.out.println(name);
User user = new User(1L,"格雷福斯");
Optional<User> userOptional = Optional.ofNullable(user);// 为null直接返回`Supplier`生产型函数接口返回的对象
String name = userOptional.orElseGet(() new User(0L,"添甄")).getName();
System.out.println(name);
User user = new User(1L,"格雷福斯");
Optional<User> userOptional = Optional.ofNullable(user);// 如果数据为null,抛出 指定异常
String name = userOptional.orElseThrow(() new RuntimeException("无数据")).getName();
System.out.println(name);
User user = new User(1L,"格雷福斯");
Optional<User> userOptional = Optional.ofNullable(user);// 过滤名字长度大于3,如果有值才输出,没值就不输出
userOptional.filter(item -> item.getName().length()>3).ifPresent(System.out::println);
1.
2.
3.
4.
5.
map(Function mapper)
作用:如果optional不为空,则将optional中的对象 t 映射成另外一个对象 u,并将 u 存放到一个新的optional容器中,该方法与Stream的map作用一样
源码:
代码实现:
User user = new User(1L,"格雷福斯");
Optional<User> userOptional = Optional.ofNullable(user);// 只获取用户名
String name = userOptional.map(User::getName).orElse("添甄");
System.out.println(name);
User user = new User(1L,"格雷福斯");
Optional<User> userOptional = Optional.ofNullable(null);
Optional<String> optional = userOptional.flatMap(item -> Optional.ofNullable(item.getName()));
String name = optional.orElse("添甄");
System.out.println(name);
1.
2.
3.
4.
5.
错误示范
获取用户名:
User user = new User(1L,"格雷福斯");
Optional<User> userOptional = Optional.ofNullable(user);// 判断是否有值
if (userOptional.isPresent()){
String name = userOptional.get().getName();
System.out.println(name);}else {
System.out.println("无值");}
1.
2.
3.
4.
5.
6.
7.
8.
9.
通过调用isPresent方法判断是否有值,这还是增加了判断,破坏代码结构
正确姿势:
多用map,orElse,filter方法发挥Optional的作用
User user = new User(1L,"格雷福斯");
Optional<User> userOptional = Optional.ofNullable(user);
String name = userOptional.map(User::getName).orElse("无值");
System.out.println(name);