public class java8optionaltest {
list<string> stringlist = null;
icar car = new weilaicar();
}
public class weilaicar implements icar {
integer wheels = new integer(4);
}
public static <t> optional<t> of(t value) {
return new optional<>(value);
}
public static <t> optional<t> ofnullable(t value) {
return value == null ? empty() : of(value);
}
public static<t> optional<t> empty() {
@suppresswarnings("unchecked")
optional<t> t = (optional<t>) empty;
return t;
}
1、empty支持你去创建一个空的optional类,这样的类直接get()会报错:java.util.nosuchelementexception: no value present
2、of(x)传入的对象不能为null,而ofnullable(x)是支持传入null的对象,一般用这两个比较多。 present 方法
ispresent是用来判断optional中对象是否为null,ifpresent的参数是当对象不为null时执行的lamdba表达式。
public boolean ispresent() {
return value != null;
}
public void ifpresent(consumer<? super t> consumer) {
if (value != null)
consumer.accept(value);
}
示例详解介绍了ifpresent特性:
java8optionaltest test = new java8optionaltest();
optional<java8optionaltest> optional = optional.of(test);
pringtest(optional.ispresent());
//true
optional.ifpresent( a -> pringtest(a.getcar().getclass().getname()));
//com.ts.util.optional.weilaicar
optional.ifpresent( a -> optional.ofnullable(a.getstringlist()).ifpresent(b -> pringtest("stringlist:" + (b == null))));
//第一级的ifpresent是存在test对象,所以执行了lambda表达式,而第二级的ifpresent的stringlist是null,所以没有执行表达式
optional.ifpresent( a -> optional.ofnullable(a.getcar()).ifpresent(b -> pringtest("car:" + (b == null))));
//car:false
//第二级ifpresent的car对象是存在的,所以第二级的表达式执行了
public optional<t> filter(predicate<? super t> predicate) {
objects.requirenonnull(predicate);
if (!ispresent())
return this;
else
return predicate.test(value) ? this : empty();
}
public t orelse(t other) {
return value != null ? value : other;
}
public t orelseget(supplier<? extends t> other) {
return value != null ? value : other.get();
}
public <x extends throwable> t orelsethrow(supplier<? extends x> exceptionsupplier) throws x {
if (value != null) {
return value;
} else {
throw exceptionsupplier.get();
}
}
测试用例如下:
java8optionaltest one = null;
java8optionaltest test = new java8optionaltest();
optional<java8optionaltest> optional = optional.ofnullable(one);
pringtest(optional);
//optional.empty
pringtest(optional.orelse(test));
//com.ts.util.java8optionaltest@5197848c
pringtest(optional.orelseget(() -> new java8optionaltest()));
//com.ts.util.java8optionaltest@5d6f64b1
pringtest(optional.orelsethrow(() -> new runtimeexception("orelsethrow")));
//java.lang.runtimeexception: orelsethrow