Optional 类主要解决平时敲代码中 空指针异常(NullPointerException)
简单来说就是一个工具类
Optional 类主要 方法
1. Optional.empty() 空对象
2 Optional.of(T) 确定不为空对象传过去
3 Optional.ofNullable() ; 可能不为空的对象 发现方法实现 是上面两个的整合 return value == null ? empty() : of(value);
案列
boolean isPresent()
如果值存在则方法会返回true,否则返回 false。
@Test public void test01(){ String str = null; Optional<String> str1 = Optional.ofNullable(str); if(str1.isPresent()){ System.out.println("存在值"); }else{ System.out.println("不存在值"); } String strs = "Hello World"; Optional<String> str2 = Optional.ofNullable(strs); if(str2.isPresent()){ System.out.println("存在值"); }else{ System.out.println("不存在值"); }
boolean present = Optional.ofNullable(strs).isPresent();
String s = str2.get(); //取值
}
T orElse(T other)
如果存在该值,返回值, 否则返回 other。
T orElseGet(Supplier<? extends T> other)
如果存在该值,返回值, 否则触发 other,并返回 other 调用的结果。
@Test public void test02(){ String str = null; String value = Optional.ofNullable(str).orElse("default value"); System.out.println(value); String str1 = "Hello World"; String value1 = Optional.ofNullable(str1).orElse("default value"); System.out.println(value1); // default value // Hello World }
区别 在于 orElse方法无论是传入值否为空都会执行 orElseGet 方法为空时执行 不为空时不执行
@Test public void test04() { Integer value1 = null; Integer value2 = 10; Optional<Integer> a = Optional.ofNullable(value1); Optional<Integer> b = Optional.of(value2); System.out.println(b.orElse(getDefaultValue())); // 调用getDefaultValue System.out.println(a.orElse(getDefaultValue())); // 调用getDefaultValue System.out.println(b.orElseGet(() -> getDefaultValue())); // 不调用getDefaultValue System.out.println(a.orElseGet(() -> getDefaultValue())); // 调用getDefaultValue // 调用10 // 调用0 // 10 // 调用0 } public static Integer getDefaultValue() { System.out.print(" 调用"); return new Integer(0); }
原文:https://www.cnblogs.com/lccsdncnblogs/p/java8_Optional.html