package java.util;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;/**
* @since 1.8*/
public final class Optional{private static final Optional> EMPTY = new Optional<>();privatefinal T value;privateOptional() {this.value = null;
}//返回一个空的 Optional实例
public static Optionalempty() {
@SuppressWarnings("unchecked")
Optional t = (Optional) EMPTY;returnt;
}privateOptional(T value) {this.value =Objects.requireNonNull(value);
}//返回具有 Optional的当前非空值的Optional
public static Optionalof(T value) {return new Optional<>(value);
}//返回一个 Optional指定值的Optional,如果非空,则返回一个空的 Optional
public static OptionalofNullable(T value) {return value == null ?empty() : of(value);
}//如果Optional中有一个值,返回值,否则抛出 NoSuchElementException 。
public T get() {if (value == null) {throw new NoSuchElementException("No value present");
}returnvalue;
}//返回true如果存在值,否则为 false
publicboolean isPresent() {return value != null;
}//如果存在值,则使用该值调用指定的消费者,否则不执行任何操作。
public void ifPresent(Consumer super T>consumer) {if (value != null)
consumer.accept(value);
}//如果一个值存在,并且该值给定的谓词相匹配时,返回一个 Optional描述的值,否则返回一个空的 Optional
public Optional filter(Predicate super T>predicate) {
Objects.requireNonNull(predicate);if (!isPresent())return this;else
return predicate.test(value) ? this: empty();
}//如果存在一个值,则应用提供的映射函数,如果结果不为空,则返回一个 Optional结果的 Optional 。
public Optional map(Function super T, ? extends U>mapper) {
Objects.requireNonNull(mapper);if (!isPresent())returnempty();else{returnOptional.ofNullable(mapper.apply(value));
}
}//如果一个值存在,应用提供的 Optional映射函数给它,返回该结果,否则返回一个空的 Optional 。
public Optional flatMap(Function super T, Optional>mapper) {
Objects.requireNonNull(mapper);if (!isPresent())returnempty();else{returnObjects.requireNonNull(mapper.apply(value));
}
}//如果值存在,就返回值,不存在就返回指定的其他值
publicT orElse(T other) {return value != null ?value : other;
}public T orElseGet(Supplier extends T>other) {return value != null ? value : other.get();
}public T orElseThrow(Supplier extends X>exceptionSupplier) throws X {if (value != null) {returnvalue;
}else{throw exceptionSupplier.get();
}
}
}
关于of方法,现在好像很流行,就是提供一个static方法,方法名称叫of,方法的返回值返回当前类,并且把构造函数设置为私有private,用静态of方法来代替构造函数。public classUser {privateString username;privateInteger age;privateUser() {
}public staticUser of() {return newUser();
}privateUser(String username, Integer age) {this.username =username;this.age =age;
}public staticUser of(String username, Integer age) {return newUser(username, age);
}
}
Mainpublic static voidmain(String[] args) {//Optional类已经成为Java 8类库的一部分,在Guava中早就有了,可能Oracle是直接拿来使用了//Optional用来解决空指针异常,使代码更加严谨,防止因为空指针NullPointerException对代码造成影响
String msg = "hello";
Optional optional =Optional.of(msg);//判断是否有值,不为空
boolean present =optional.isPresent();//如果有值,则返回值,如果等于空则抛异常
String value = optional.get();//如果为空,返回else指定的值
String hi = optional.orElse("hi");//如果值不为空,就执行Lambda表达式
optional.ifPresent(opt -> System.out.println(opt));
}