创立一个Optional
1、创立一个能够蕴含null的Optional
Optional<String> optional = Optional.ofNullable(null);
2、创立一个蕴含null的Optional
Optional<Object> empty = Optional.empty();
这两个代码的意思是统一的
3、创立一个不能蕴含null的Optional
Optional<String> optional = Optional.of("abc"); public static <T> Optional<T> of(T value) { return new Optional<>(value); } private Optional(T value) { this.value = Objects.requireNonNull(value); } public static <T> T requireNonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; }
从代码调用过程来看,of办法不能接管null值,否则会间接抛出空指针异样。
判断是否null
1、应用isPresent()来判断是否为null
Optional<String> optional = Optional.of("abc"); System.out.println(optional.isPresent());//true Optional<String> empty = Optional.empty(); System.out.println(empty.isPresent());//false Optional<String> nullOption = Optional.ofNullable(null); System.out.println(nullOption.isPresent());//false
Option类中的其余办法
这边会波及到一些Consumer、Supplier、用法,能够先参考我的另外一篇文章疾速了解Consumer、Supplier、Predicate与Function
get(),获取值
public T get() { if (value == null) { throw new NoSuchElementException("No value present"); } return value; }
看进去,get()只能用于不为null的状况下,否则间接抛出NoSuchElementException异样
ifPresent(),如果不为null,则去进行生产
public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }
orElseGet(),如果为null,则应用Supplier中供应的值
public T orElseGet(Supplier<? extends T> other) { return value != null ? value : other.get(); }
orElse(),如果为null,则间接应用传入的值
public T orElse(T other) { return value != null ? value : other; }
orElseThrow(),如果为null,则抛出某种异样
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { if (value != null) { return value; } else { throw exceptionSupplier.get(); } }
除了以上的办法,还有map、flatmap、filter等,这些办法和Stream中的同名办法相似,只不过Optional中的这些办法返回一个Option,而Stream中返回一个Stream。
应用Option来革新你的代码
外汇赠金流动https://www.kaifx.cn/activity/
示例1:输入用户的id
//革新前 if (user!=null){ System.out.println(user.getId()); } //革新后 Optional.ofNullable(user) .map(User::getId) .ifPresent(System.out::println);
示例2:当用户没有年龄时,应用默认值20岁
//革新前 int age1 = 0; if (user != null) { if (user.getAge() == null) { age1 = 20; } else { age1 = user.getAge(); } } //革新后 int age2 = Optional.ofNullable(user) .map(User::getId) .orElse(20);
示例3:当用户的姓名为空时,抛出异样
//革新前 if (user != null) { String name = user.getName(); if (name == null) { throw new Exception(); } } //革新后 Optional.ofNullable(user) .map(User::getName) .orElseThrow(Exception::new);
示例4:当用户的年龄大于18岁时,输入一个其大写模式的姓名,当姓名不存在时,输入Unknown
//革新前 if (user != null) { int age = user.getAge(); if (age > 18) { String name = user.getName(); if (name != null) { System.out.println(name); } else { System.out.println("Unknown"); } } } //革新后 Optional.ofNullable(user) .filter(u -> u.getAge() > 18) .map(User::getName) .map(String::toUpperCase) .or(() -> Optional.of("Unknown")) .ifPresent(System.out::println);