加载中

One of the most interesting features that Java 8 introduced to the language was the Optional class. The main issue this class is intended to tackle is the infamous NullPointerException that every Java programmer knows only too well.

Essentially, this is a wrapper class that contains an optional value, meaning it can either contain an object or it can simply be empty.

Optional comes along with a strong move towards functional programming in Java and is meant to help in that paradigm, but definitely also outside of that.

从 Java 8 引入的一个很有趣的特性是 Optional  类。Optional 类主要解决的问题是臭名昭著的空指针异常(NullPointerException) —— 每个 Java 程序员都非常了解的异常。

本质上,这是一个包含有可选值的包装类,这意味着 Optional 类既可以含有对象也可以为空。

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

Let’s start with a simple use-case. Before Java 8, any number of operations involving accessing an object’s methods or properties could result in a NullPointerException:

String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();

If we wanted to make sure we won’t hit the exception in this short example, we would need to do explicit checks for every value before accessing it:

if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        Country country = address.getCountry();
        if (country != null) {
            String isocode = country.getIsocode();
            if (isocode != null) {
                isocode = isocode.toUpperCase();
            }
        }
    }
}

As you can see, this can easily become cumbersome and hard to maintain.

To ease this process, let’s take a look at how we can use the Optional class instead, from creating and verifying an instance, to using the different methods it provides and combining it with other methods that return the same type, the latter being where the true power of Optional lies.

我们从一个简单的用例开始。在 Java 8 之前,任何访问对象方法或属性的调用都可能导致 NullPointerException

String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();

在这个小示例中,如果我们需要确保不触发异常,就得在访问每一个值之前对其进行明确地检查:

if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        Country country = address.getCountry();
        if (country != null) {
            String isocode = country.getIsocode();
            if (isocode != null) {
                isocode = isocode.toUpperCase();
            }
        }
    }
}

你看到了,这很容易就变得冗长,难以维护。

为了简化这个过程,我们来看看用 Optional  类是怎么做的。从创建和验证实例,到使用其不同的方法,并与其它返回相同类型的方法相结合,下面是见证 Optional  奇迹的时刻。

Creating Optional Instances

To reiterate, an object of this type can contain a value or be empty. You can create an empty Optional by using the method with the same name:

@Test(expected = NoSuchElementException.class)
public void whenCreateEmptyOptional_thenNull() {
    Optional<User> emptyOpt = Optional.empty();
    emptyOpt.get();
}

Not surprisingly, attempting to access the value of the emptyOpt variable results in a NoSuchElementException.

To create an Optional object that can contain a value – you can use the of() and ofNullable() methods. The difference between the two is that the of() method will throw a NullPointerException if you pass it a null value as an argument:

@Test(expected = NullPointerException.class)
public void whenCreateOfEmptyOptional_thenNullPointerException() {
    Optional<User> opt = Optional.of(user);
}

As you can see, we’re not completely rid of the NullPointerException. For this reason, you should only use of() when you are sure the object is not null.

If the object can be both null or not-null, then you should instead choose the ofNullable() method:

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

创建 Optional  实例

重申一下,这个类型的对象可能包含值,也可能为空。你可以使用同名方法创建一个空的 Optional。

@Test(expected = NoSuchElementException.class)
public void whenCreateEmptyOptional_thenNull() {
    Optional<User> emptyOpt = Optional.empty();
    emptyOpt.get();
}

毫不奇怪,尝试访问 emptyOpt 变量的值会导致 NoSuchElementException

你可以使用  of() 和 ofNullable() 方法创建包含值的 Optional。两个方法的不同之处在于如果你把 null 值作为参数传递进去,of() 方法会抛出 NullPointerException

@Test(expected = NullPointerException.class)
public void whenCreateOfEmptyOptional_thenNullPointerException() {
    Optional<User> opt = Optional.of(user);
}

你看,我们并没有完全摆脱 NullPointerException。因此,你应该明确对象不为 null  的时候使用 of()

如果对象即可能是 null 也可能是非 null,你就应该使用 ofNullable() 方法:

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

Accessing the Value of Optional Objects

One way to retrieve the actual object inside the Optional instance is to use the get() method:

@Test
public void whenCreateOfNullableOptional_thenOk() {
    String name = "John";
    Optional<String> opt = Optional.ofNullable(name);

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

However, as you saw before, this method throws an exception in case the value is null. To avoid this exception, you can choose to first verify if a value is present or not:

@Test
public void whenCheckIfPresent_thenOk() {
    User user = new User("john@gmail.com", "1234");
    Optional<User> opt = Optional.ofNullable(user);
    assertTrue(opt.isPresent());

    assertEquals(user.getEmail(), opt.get().getEmail());
}

Another option for checking the presence of a value is the ifPresent() method. In addition to performing the check, this method also takes a Consumer argument and executes the lambda expression if the object is not empty:

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

In this example, the assertion is only executed if the user object is not null.

Next, let’s look at ways in which alternatives for empty values can be provided.

访问 Optional 对象的值

从 Optional 实例中取回实际值对象的方法之一是使用 get() 方法:

@Test
public void whenCreateOfNullableOptional_thenOk() {
    String name = "John";
    Optional<String> opt = Optional.ofNullable(name);

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

不过,你看到了,这个方法会在值为 null 的时候抛出异常。要避免异常,你可以选择首先验证是否有值:

@Test
public void whenCheckIfPresent_thenOk() {
    User user = new User("john@gmail.com", "1234");
    Optional<User> opt = Optional.ofNullable(user);
    assertTrue(opt.isPresent());

    assertEquals(user.getEmail(), opt.get().getEmail());
}

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

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

这个例子中,只有 user 用户不为 null 的时候才会执行断言。

接下来,我们来看看提供空值的方法。

Returning Default Values

The Optional class provides APIs for returning the value of the object or a default value if the object is empty.

The first method you can use for this purpose is orElse(), which works in a very straight-forward way: it returns the value if it’s present, or the argument it receives if not:

@Test
public void whenEmptyValue_thenReturnDefault() {
    User user = null;
    User user2 = new User("anna@gmail.com", "1234");
    User result = Optional.ofNullable(user).orElse(user2);

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

Here, the user object was null, so user2 was returned as a default instead.

If the initial value of the object is not null, then the default value is ignored:

@Test
public void whenValueNotNull_thenIgnoreDefault() {
    User user = new User("john@gmail.com","1234");
    User user2 = new User("anna@gmail.com", "1234");
    User result = Optional.ofNullable(user).orElse(user2);

    assertEquals("john@gmail.com", result.getEmail());
}

The second API in the same category is orElseGet() – which behaves in a slightly different manner. In this case, the method returns the value if one is present, and if not it executes the Supplier functional interface that it receives as an argument, and returns the result of that execution:

User result = Optional.ofNullable(user).orElseGet( () -> user2);

返回默认值

Optional 类提供了 API 用以返回对象值,或者在对象为空的时候返回默认值。

这里你可以使用的第一个方法是 orElse(),它的工作方式非常直接,如果有值则返回该值,否则返回传递给它的参数值:

@Test
public void whenEmptyValue_thenReturnDefault() {
    User user = null;
    User user2 = new User("anna@gmail.com", "1234");
    User result = Optional.ofNullable(user).orElse(user2);

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

这里 user 对象是空的,所以返回了作为默认值的 user2

如果对象的初始值不是 null,那么默认值会被忽略:

@Test
public void whenValueNotNull_thenIgnoreDefault() {
    User user = new User("john@gmail.com","1234");
    User user2 = new User("anna@gmail.com", "1234");
    User result = Optional.ofNullable(user).orElse(user2);

    assertEquals("john@gmail.com", result.getEmail());
}

第二个同类型的 API 是 orElseGet() —— 其行为略有不同。这个方法会在有值的时候返回值,如果没有值,它会执行作为参数传入的 Supplier(供应者) 函数式接口,并将返回其执行结果:

User result = Optional.ofNullable(user).orElseGet( () -> user2);

Difference Between orElse() and orElseGet()

At first glance, it might seem as if the two methods have the same effect. However, this is not exactly the case. Let’s create some examples that highlight the similarities as well as the differences in behavior between the two.

First, let’s see how they behave when an object is empty:

@Test
public void givenEmptyValue_whenCompare_thenOk() {
    User user = null
    logger.debug("Using orElse");
    User result = Optional.ofNullable(user).orElse(createNewUser());
    logger.debug("Using orElseGet");
    User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
}

private User createNewUser() {
    logger.debug("Creating New User");
    return new User("extra@gmail.com", "1234");
}

In the code above, both methods call the createNewUser() method which logs a message and returns a User object.

The output of this code is:

Using orElse
Creating New User
Using orElseGet
Creating New User

Therefore, when the object is empty and the default object is returned instead, there is no difference in behavior.

orElse() 和 orElseGet() 的不同之处

乍一看,这两种方法似乎起着同样的作用。然而事实并非如此。我们创建一些示例来突出二者行为上的异同。

我们先来看看对象为空时他们的行为:

@Test
public void givenEmptyValue_whenCompare_thenOk() {
    User user = null
    logger.debug("Using orElse");
    User result = Optional.ofNullable(user).orElse(createNewUser());
    logger.debug("Using orElseGet");
    User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
}

private User createNewUser() {
    logger.debug("Creating New User");
    return new User("extra@gmail.com", "1234");
}

上面的代码中,两种方法都调用了 createNewUser() 方法,这个方法会记录一个消息并返回 User 对象。

代码输出如下:

Using orElse
Creating New User
Using orElseGet
Creating New User

由此可见,当对象为空而返回默认对象时,行为并无差异。

Next, let’s take a look at a similar example in which the Optional is not empty:

@Test
public void givenPresentValue_whenCompare_thenOk() {
    User user = new User("john@gmail.com", "1234");
    logger.info("Using orElse");
    User result = Optional.ofNullable(user).orElse(createNewUser());
    logger.info("Using orElseGet");
    User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
}

The output this time is:

Using orElse
Creating New User
Using orElseGet

Here, both Optional objects contain a non-null value which the methods will return. However, the orElse() method will still create the default User object. By contrast, the orElseGet() method will no longer create a User object.

This difference can have a significant effect on performance if the operation executed involves more intensive calls, such as a web service call or a database query.

我们接下来看一个类似的示例,但这里 Optional  不为空:

@Test
public void givenPresentValue_whenCompare_thenOk() {
    User user = new User("john@gmail.com", "1234");
    logger.info("Using orElse");
    User result = Optional.ofNullable(user).orElse(createNewUser());
    logger.info("Using orElseGet");
    User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
}

这次的输出:

Using orElse
Creating New User
Using orElseGet

这个示例中,两个 Optional  对象都包含非空值,两个方法都会返回对应的非空值。不过,orElse() 方法仍然创建了 User 对象。与之相反,orElseGet() 方法不创建 User 对象。

在执行较密集的调用时,比如调用 Web 服务或数据查询,这个差异会对性能产生重大影响

Returning an Exception

Next to the orElse() and orElseGet() methods, Optional also defines an orElseThrow() API – which, instead of returning an alternate value, throws an exception instead if the object is empty:

@Test(expected = IllegalArgumentException.class)
public void whenThrowException_thenOk() {
    User result = Optional.ofNullable(user)
      .orElseThrow( () -> new IllegalArgumentException());
}

Here, if the user value is null, an IllegalArgumentException is thrown.

This allows us to have a lot more flexible semantics and decide the exception that gets thrown instead of always seeing a NullPointerException.

Now that we have a good understanding of how we can leverage Optional by itself, let’s have a look at additional methods that can be used to apply transformations and filtering to Optional values.

返回异常

除了 orElse() 和 orElseGet() 方法,Optional 还定义了 orElseThrow() API —— 它会在对象为空的时候抛出异常,而不是返回备选的值:

@Test(expected = IllegalArgumentException.class)
public void whenThrowException_thenOk() {
    User result = Optional.ofNullable(user)
      .orElseThrow( () -> new IllegalArgumentException());
}

这里,如果 user 值为 null,会抛出 IllegalArgumentException

这个方法让我们有更丰富的语义,可以决定抛出什么样的异常,而不总是抛出 NullPointerException

现在我们已经很好地理解了如何使用 Optional,我们来看看其它可以对 Optional 值进行转换和过滤的方法。

Transforming Values

Optional values can be transformed in a number of ways; let’s start with map() and flatMap() methods.

First, let’s see an example that uses the map() API:

@Test
public void whenMap_thenOk() {
    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() applies the Function argument to the value, then returns the result wrapped in an Optional. This makes it possible to apply and chain further operations on the response – such orElse() here.

By comparison, flatMap() also takes a Function argument that is applied to an Optional value, and then returns the result directly.

To see this in action, let’s add a method that returns an Optional to the User class:

public class User {    
    private String position;

    public Optional<String> getPosition() {
        return Optional.ofNullable(position);
    }

    //...
}

Since the getter method returns an Optional of String value, you can use as the argument for flatMap(), where this is called for an Optional User object. The return will be the unwrapped String value:

@Test
public void whenFlatMap_thenOk() {
    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());
}

转换值

有很多种方法可以转换 Optional  的值。我们从 map() 和 flatMap() 方法开始。

先来看一个使用 map() API 的例子:

@Test
public void whenMap_thenOk() {
    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 中。这就使对返回值进行链试调用的操作成为可能 —— 这里的下一环就是 orElse()

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

下面的操作中,我们给 User 类添加了一个方法,用来返回 Optional

public class User {    
    private String position;

    public Optional<String> getPosition() {
        return Optional.ofNullable(position);
    }

    //...
}

既然 getter 方法返回 String 值的 Optional,你可以在对 User 的 Optional 对象调用 flatMap() 时,用它作为参数。其返回的值是解除包装的 String 值:

@Test
public void whenFlatMap_thenOk() {
    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());
}

Filtering Values

Alongside transforming the values, the Optional class also offers the possibility to “filter” them based on a condition.

The filter() method takes a Predicate as an argument and returns the value as it is if the test evaluates to true. Otherwise, if the test is false, the returned value is an empty Optional.

Let’s see an example of accepting or rejecting a User based on a very basic email verification:

@Test
public void whenFilter_thenOk() {
    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());
}

The result object will contain a non-null value as a result of it passing the filter test.

过滤值

除了转换值之外,Optional  类也提供了按条件“过滤”值的方法。

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

来看一个根据基本的电子邮箱验证来决定接受或拒绝 User(用户) 的示例:

@Test
public void whenFilter_thenOk() {
    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());
}

如果通过过滤器测试,result 对象会包含非空值。

返回顶部
顶部
返回顶部
顶部