Java8特性:Optional空值处理
程序员文章站
2022-06-07 16:06:26
...
Optional常用方法
- isPresent()方法当Optional实例的值非空时返回true,否则返回false;
-
orElseGet()方法当Optional包含非空值时返回该值,否则通过接收的function生成一个默认的;
-
map()方法转换当前Optional的值,并返回一个新的Optional实例;
-
orElse()方法与orElseGet方法相似,不同的是orElse()直接返回传入的默认值。
实列
- 有值的时候
public static void main(String args[]) {
Optional<String> fullName = Optional.ofNullable("存放值");
System.out.println("Full Name is set? " + fullName.isPresent());
System.out.println("Full Name: " + fullName.orElseGet(() -> "[none]"));
System.out.println(fullName.map(s -> "Hey " + s + "!").orElse("Hey Stranger!"));
}
- 没有值的时候
public static void main(String args[]) {
Optional<String> fullName = Optional.ofNullable(null);
System.out.println("Full Name is set? " + fullName.isPresent());
System.out.println("Full Name: " + fullName.orElseGet(() -> "[none]"));
System.out.println(fullName.map(s -> "Hey " + s + "!").orElse("Hey Stranger!"));
}
- get()方法主要用于返回包装对象的实际值,但是如果包装对象值为null,会抛出NoSuchElementException异常
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
- isPresent()方法用于判断包装对象的值是否非空
public boolean isPresent() {
return value != null;
}
- ifPresent()方法接受一个Consumer对象(消费函数),如果包装对象的值非空,运行Consumer对象的accept()方法,实列如第二个
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
public static void printName(Student student)
{
Optional.ofNullable(student).ifPresent(u -> System.out.println("The student name is : " + u.getName()));
}
- filter()方法接受参数为Predicate对象,用于对Optional对象进行过滤,如果符合Predicate的条件,返回Optional对象本身,否则返回一个空的Optional对象
public static void filterAge(Student student)
{
Optional.ofNullable(student).filter( u -> u.getAge() > 18).ifPresent(u -> System.out.println("The student age is more than 18."));
}
- map()方法的参数为Function(函数式接口)对象,map()方法将Optional中的包装对象用Function函数进行运算,并包装成新的Optional对象(包装对象的类型可能改变)
public static Optional<Integer> getAge(Student student)
{
return Optional.ofNullable(student).map(u -> u.getAge());
}
- 跟map()方法不同的是,入参Function函数的返回值类型为Optional类型,而不是U类型,这样flatMap()能将一个二维的Optional对象映射成一个一维的对象
public static Optional<Integer> getAge(Student student) { return Optional.ofNullable(student).flatMap(u -> Optional.ofNullable(u.getAge())); }
- orElse()方法功能比较简单,即如果包装对象值非空,返回包装对象值,否则返回入参other的值(默认值)
public static String getGender(Student student) { return Optional.ofNullable(student).map(u -> u.getGender()).orElse("Unkown"); }
- orElseGet()方法与orElse()方法类似,区别在于orElseGet()方法的入参为一个Supplier对象,用Supplier对象的get()方法的返回值作为默认值
public static String getGender(Student student) { return Optional.ofNullable(student).map(u -> u.getGender()).orElseGet(() -> "Unkown"); }
- orElseThrow()方法其实与orElseGet()方法非常相似了,入参都是Supplier对象,只不过orElseThrow()的Supplier对象必须返回一个Throwable异常
public static String getGender1(Student student) { return Optional.ofNullable(student).map(u -> u.getGender()).orElseThrow(() -> new RuntimeException("Unkown")); }
orElseThrow()方法适用于包装对象值为空时需要抛出特定异常的场景
Optional避免空指针shili
- 不用optional时候
public String getUserSteetName(User user) { if(null != user) { Address address = user.getAddress(); if(null != address) { Street street = address.getStreet(); if(null != street) { return street.getStreetName(); } } } return "nothing found";}
- 使用Optional时候
public String getUserSteetName(User user) { Optional<User> userOptional = Optional.ofNullable(user); final String streetName = userOptional.orElse(new User()).getAddress().orElse(new Address()).getStreet().orElse(new Street()).getStreetName(); return StringUtils.isEmpty(streetName) ? "nothing found" : streetName; }
参考文献
https://www.jianshu.com/p/d81a5f7c9c4e
https://www.cnblogs.com/wuhenzhidu/p/10765655.html
上一篇: 减少MySQL主从数据同步延迟
下一篇: MySQL操作类