JAVA8新特性(六)——Optional API

Optional对null提供了一个更优雅的实现。

比如我们要判断str是否为空,为空则赋值为defalut,用之前的写法是这样:

if(str!=null && !“”.equlas(str)) {
 
} else {
 str = “defalut”
}

但是,使用Oprional

Optional. ofNullable(str). orElse(“defalut”);

Optional的常用方法

of和ofNullable

of和ofNullable是用于创建Optional对象的,of不能创建null对象,而ofNullable可以。

Optional<String> str = Optional.of("sss");
//of参数为空,抛nullPointException
//Optional<String> str1 = Optional.of(null);
//ofNullable,参数可以为空,为空则返回值为空
Optional<String> str1 = Optional.ofNullable(null);

isPresent和get

isPresent是用来判断对象是否为空,get获得该对象。

if (str.isPresent()) {
    System.out.println(str.get());
}
if (str1.isPresent()) {
    System.out.println(str1.get());
}

orElse和orElseGet

orElse和orElseGet都是实现当Optional为空时,给对象赋值。orElse参数为赋值对象,orElseGet为Supplier函数接口。

//orElse
System.out.println(str.orElse("There is no value present!"));
System.out.println(str1.orElse("There is no value present!"));

//orElseGet,设置默认值
System.out.println(str.orElseGet(() -> "default value"));
System.out.println(str1.orElseGet(() -> "default value"));

orElseThrow

orElseThrow是当存在null时,抛出异常。

try {
    //orElseThrow
    str1.orElseThrow(Exception::new);
} catch (Throwable ex) {
    //输出: No value present in the Optional instance
    System.out.println(ex.getMessage());
}

map和flatmap

map和flatmap都是映射,即将Optional中的对象通过Function函数接口转成其他对象。map的函数接口的参数是T,而flatmap的参数是Optional对象

//map
Optional<String> upperName = str.map((value) -> value.toUpperCase());
System.out.println(upperName.orElse("default value"));
Optional<String> upperName1 = str1.map((value) -> value.toUpperCase());
System.out.println(upperName1.orElse("default value"));

//flatmap
upperName = str.flatMap((value) -> Optional.of(value.toUpperCase()));
System.out.println(upperName.orElse("No value found"));

filter

filter是过滤器,参数是Predicate接口。过滤不过对象返回null。

//filter,参数是Predicate接口
Optional<String> newStr = str.filter((value) -> value.length() > 5);
System.out.println(newStr.orElse("str length is less than 5"));

猜你喜欢

转载自blog.csdn.net/luo4105/article/details/78043727