JDK8中Optional简介说明
下文笔者讲述Optional简介说明,如下所示
Optional简介
Jdk8中对外提供Optional 一个可包含null值容器对象 可用于替换xx != null判断
Optional中常用方法
of
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
为value创建一个Optional对象
当value为空时,会报NullPointerException异常
ofNullable
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
为value创建一个Optional对象
但可允许value为null值
isPresent
public boolean isPresent() {
return value != null;
}
判断当前value是否为null
如果不为null则返回true
否则false
ifPresent
当不为null值就执行函数式接口的内容
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
get
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
返回当前的值
如果为空则报异常
orElse
返回当前值
当为null则返回other。
public T orElse(T other) {
return value != null ? value : other;
}
orElseGet
orElseGet和orElse类似
orElseGet支持函数式接口来生成other值
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
orElseThrow
当有值则返回
没有则用函数式接口抛出生成的异常
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
Optional示例
public static void main(String[] args) {
testOf();
testNullable();
}
private static void testNullable() {
User user = null;
User maomao = new User("maomao",22);
User gougou = new User("gougou",16);
System.out.println(Optional.ofNullable(user).orElse(maomao));
System.out.println(Optional.ofNullable(maomao).get());
System.out.println(Optional.ofNullable(gougou).orElse(maomao));
System.out.println(Optional.ofNullable(user).orElseGet(() -> maomao));
System.out.println();
}
private static void testOf() {
try {
User user1 = new User();
Optional<User> userOptional1 = Optional.of(user1);
if (userOptional1.isPresent()) {
System.out.println("user is not null");
}
User user2 = null;
Optional<User> userOptional2 = Optional.of(user2);//NullPointerException
if (userOptional2.isPresent()) {
System.out.println("user is not null");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println();
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


