Java Optional使用

Optional

一、Optional 简介

Opitonal是java8引入的一个新类,目的是为了解决空指针异常问题。本质上,这是一个包含有可选值的包装类,这意味着 Optional 类既可以含有对象也可以为空。

Optional 是 Java 实现函数式编程的强劲一步,并且帮助在范式中实现。但是 Optional 的意义显然不止于此。


二、创建 Optional 实例

2.1 empty()方法
Optional<User> emptyOpt = Optional.empty();
emptyOpt.get();

尝试访问 emptyOpt 变量的值会导致 NoSuchElementException。

2.2 of() 方法
Optional<User> opt = Optional.of(user);

如果你把 null 值作为参数传递进去,of() 方法会抛出 NullPointerException

2.3 ofNullable() 方法
Optional<User> opt = Optional.ofNullable(user);

如果你把 null 值作为参数传递进去,ofNullable() 方法不会抛出 NullPointerException

因此,你应该明确对象不为 null 的时候使用 of()。如果对象即可能是 null 也可能是非 null,你就应该使用 ofNullable() 方法。


三、Optional的使用

3.1 访问 Optional 对象的值

3.1.1 get() 方法
String name = "John";
Optional<String> opt = Optional.ofNullable(name);

assertEquals("John", opt.get());

这个方法会在值为 null的时候抛出异常。

3.1.2 isPresent()方法
User user = new User("john@gmail.com", "1234");
Optional<User> opt = Optional.ofNullable(user);
assertTrue(opt.isPresent());

assertEquals(user.getEmail(), opt.get().getEmail());
3.1.3 ifPresent()方法

该方法除了执行检查,还接受一个Consumer(消费者) 参数,如果对象不是空的,就对执行传入的 Lambda 表达式:

opt.ifPresent( u -> assertEquals(user.getEmail(), u.getEmail()));

3.2 返回默认值

3.2.1 orElse()方法

Optional类提供了API用以返回对象值,或者在对象为空的时候返回默认值:orElse(),
如果有值则返回该值,否则返回传递给它的参数值:

User user2 = new User("anna@gmail.com", "1234");
User result = Optional.ofNullable(user).orElse(user2);

assertEquals(user2.getEmail(), result.getEmail());

这里 user 对象是空的,所以返回了作为默认值的 user2。如果对象的初始值不是 null,那么默认值会被忽略。

3.2.2 orElseGet()方法

这个方法会在有值的时候返回值,如果没有值,它会执行作为参数传入的 Supplier(供应者) 函数式接口,并将返回其执行结果:

User result = Optional.ofNullable(user).orElseGet( () -> user2);
3.2.3 orElse() 和 orElseGet() 的不同之处
  • 对象为空时两者的行为都会执行。
  • 对象不为空时,orElse()方法中的行为会执行,而orElseGet()方法中的行为不会执行。在执行较密集的调用时,比如调用 Web 服务或数据查询,这个差异会对性能产生重大影响。

3.3 返回异常

3.3.1 orElseThrow()方法
User result = Optional.ofNullable(user).orElseThrow( () -> new IllegalArgumentException());

3.4 转换值

3.4.1 map()方法
User user = new User("anna@gmail.com", "1234");
String email = Optional.ofNullable(user)
.map(u -> u.getEmail()).orElse("default@gmail.com");

assertEquals(email, user.getEmail());

map() 对值应用(调用)作为参数的函数,然后将返回的值包装在 Optional 中。这就使对返回值进行链试调用的操作成为可能。

注意:如果map中操作对象为空,直接返回Optional.empty。

见源码,isPresent()先判断Optional中对象是否为null:

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
	Objects.requireNonNull(mapper);
	if (!isPresent())
		return empty();
	else {
		return Optional.ofNullable(mapper.apply(value));
	}
}
3.4.2 flatMap()方法

flatMap() 也需要函数作为参数,并对值调用这个函数,然后直接返回结果。

User user = new User("anna@gmail.com", "1234");
user.setPosition("Developer");
String position = Optional.ofNullable(user)
.flatMap(u -> u.getPosition()).orElse("default");

assertEquals(position, user.getPosition().get());

注意:如果flatMap中操作对象为空,直接返回Optional.empty。 原理同上。

3.4.3 map()和flatMap()的区别

map和flatMap都接收一个mapping function参数。

map和flatMap返回的都是Optional类型的数据。

当mapping function返回的是Optional类型的数据时,可以直接使用flatMap,flatMap直接返回该Optional。

当mapping function返回的不是Optional类型的数据时,使用map,因为map会进行一次Optional的包装。

3.5 过滤值

3.5.1 filter()方法

filter() 接受一个 Predicate 参数,返回测试结果为 true 的值。如果测试结果为 false,会返回一个空的 Optional。

User user = new User("anna@gmail.com", "1234");
Optional<User> result = Optional.ofNullable(user)
.filter(u -> u.getEmail() != null && u.getEmail().contains("@"));

assertTrue(result.isPresent());

注意:如果filter中操作对象为空,直接返回自身。

见源码:

public Optional<T> filter(Predicate<? super T> predicate) {
    Objects.requireNonNull(predicate);
    if (!isPresent())
        return this;
    else
        return predicate.test(value) ? this : empty();
}

3.6 Optional 类的链式方法

为了更充分的使用 Optional,你可以链接组合其大部分方法,因为它们都返回相同类似的对象。

@Test
public void whenChaining_thenOk() {
    User user = new User("anna@gmail.com", "1234");

    String result = Optional.ofNullable(user)
    .flatMap(u -> u.getAddress())
    .flatMap(a -> a.getCountry())
    .map(c -> c.getIsocode())
    .orElse("default");

    assertEquals(result, "default");
}

上面的代码可以通过方法引用进一步缩减:

String result = Optional.ofNullable(user)
.flatMap(User::getAddress)
.flatMap(Address::getCountry)
.map(Country::getIsocode)
.orElse("default");

四、Java 9 增强

Java 9 为 Optional 类添加了三个方法:or()、ifPresentOrElse() 和 stream()。

4.1 or()方法

or() 方法与 orElse() 和 orElseGet() 类似,它们都在对象为空的时候提供了替代情况。or() 的返回值是由 Supplier 参数产生的另一个 Optional 对象,可以配合flatMap使用。如果对象包含值,则 Lambda 表达式不会执行:

User result = Optional.ofNullable(user)
.or( () -> Optional.of(new User("default","1234"))).get();

assertEquals(result.getEmail(), "default");
4.2 ifPresentOrElse()方法

ifPresentOrElse() 方法需要两个参数:一个 Consumer 和一个 Runnable。如果对象包含值,会执行 Consumer 的动作,否则运行 Runnable。

如果你想在有值的时候执行某个动作,或者只是跟踪是否定义了某个值,那么这个方法非常有用:

Optional.ofNullable(user).ifPresentOrElse( u -> logger.info("User is:" + u.getEmail()),
() -> logger.info("User not found"));
4.3 stream()方法

它通过把实例转换为 Stream 对象,让你从广大的 Stream API 中受益。如果没有值,它会得到空的 Stream;有值的情况下,Stream 则会包含单一值。

User user = new User("john@gmail.com", "1234");
List<String> emails = Optional.ofNullable(user)
.stream()
.filter(u -> u.getEmail() != null && u.getEmail().contains("@"))
.map( u -> u.getEmail())
.collect(Collectors.toList());

assertTrue(emails.size() == 1);
assertEquals(emails.get(0), user.getEmail());

五、总结

Optional 是 Java 语言的有益补充 —— 它旨在减少代码中的 NullPointerExceptions,虽然还不能完全消除这些异常。

它也是精心设计,自然融入 Java 8 函数式支持的功能。

总的来说,这个简单而强大的类有助于创建简单、可读性更强、比对应程序错误更少的程序。

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值