}
常用方法
get()方法
get()方法主要用于返回包装对象的实际值,但是如果包装对象值为null,会抛出NoSuchElementException异常
public T get() {
if (value == null) {
throw new NoSuchElementException(“No value present”);
}
return value;
}
使用案例
@Test
public void testGet() {
Optional optional = Optional.of(“thinkwon”);
Optional optional1 = Optional.ofNullable(null);
System.out.println(optional.get());
System.out.println(optional1.get());
}
输出结果
thinkwon
java.util.NoSuchElementException: No value present
isPresent()方法
isPresent()方法用于判断value是否存在,不为NULL则返回true,如果为NULL则返回false
public boolean isPresent() {
return value != null;
}
使用案例
@Test
public void testIsPresent() {
Optional optional = Optional.of(“thinkwon”);
Optional optional1 = Optional.ofNullable(null);
System.out.println(optional.isPresent());
System.out.println(optional1.isPresent());
}
输出结果
true
false
注意:下面例子的用法不但没有减少null的防御性检查,而且增加了Optional包装的过程,违背了Optional设计的初衷,因此开发中要避免这种糟糕的使用
试想一下如果先用isPresent方法获得是否存在,然后决定是否调用get方法和之前的ifelse判断并无二致。
@Test
public void testIsPresent1() {
Optional optional = Optional.ofNullable(null);
if (optional.isPresent()) {
System.out.println(optional.get());
}
}
ifPresent(Consumer<? super T> consumer)方法
ifPresent()方法接受一个Consumer对象(消费函数),如果包装对象的值非空,运行Consumer对象的accept()方法
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
使用案例
@Test
public void testIfPresent() {
Optional optional = Optional.of(“thinkwon”);
optional.ifPresent(s -> System.out.println("the String is " + s));
}
输出结果
the String is thinkwon
filter()方法
filter()方法接受参数为Predic