JDK8的Optional用法

参考资料:https://www.baeldung.com/java-optional

    https://mp.weixin.qq.com/s/P2kb4fswb4MHfb0Vut_kZg

1. 描述

  Optional是java.util包中的一部分,所以要有相关的引用:

import java.util.Optional;

 

2. 创建Optional方法

2.1 empty,创建一个空的Optional

@Test
public void whenCreatesEmptyOptional_thenCorrect() {
    Optional<String> empty = Optional.empty();
    assertFalse(empty.isPresent());
}

2.2 of,创建Optional,使用of方法时,传入不能为null,否则会报NullPointerException异常:

@Test
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
    String name = "baeldung";
    Optional<String> opt = Optional.of(name);
    assertTrue(opt.isPresent());
}

2.3 ofNullable,创建Optional,ofNullable方法是允许值为null的

@Test
public void givenNonNull_whenCreatesNullable_thenCorrect() {
    String name = "baeldung";
    Optional<String> opt = Optional.ofNullable(name);
    assertTrue(optionalName.isPresent());
}

 

3. 判断Optional的值

3.1 isPrensent,判断Optional是否有值,返回boolean类型,上面几个创建例子都用了isPresent,源码:

public boolean isPresent() {
    return value != null;
} 

3.2 ifPrensent,如果Optional有值,执行后面函数

@Test
public void givenOptional_whenIfPresentWorks_thenCorrect() {
    Optional<String> opt = Optional.of("baeldung");
    opt.ifPresent(name -> System.out.println(name.length()));
}

  如果在Optional为null的情况下,直接使用ifPresent有可能会报NullPointerException,所以就有了下面几个函数。

3.3 orElse和orElseGet,返回Optional包裹的值,如果值为null,则返回函数内的默认值,这两个方法的区别在于orElse后面跟默认值对象,orElseGet跟的是表达式函数。

@Test
public void whenOrElseWorks_thenCorrect() {
    String nullName = null;
    String name = Optional.ofNullable(nullName).orElse("john");
    assertEquals("john", name);
}

@Test
public void whenOrElseGetWorks_thenCorrect() {
    String nullName = null;
    String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
    assertEquals("john", name);
}

3.4 orElseThrow,返回Optional包裹的值,如果值为null,则抛出异常

@Test(expected = IllegalArgumentException.class)
public void whenOrElseThrowWorks_thenCorrect() {
    String nullName = null;
    String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new);
}

3.5 get,返回Optional包裹的值,如果值为null,会抛出NoSuchElementException异常

@Test(expected = NoSuchElementException.class)
public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() {
    Optional<String> opt = Optional.ofNullable(null);
    String name = opt.get();
}

 

4. Optional值的操作

4.1 map,将一个值转换成另一个值,下面的例子是返回字符串的长度,没有则返回默认值0

@Test
public void givenOptional_whenMapWorks_thenCorrect2() {
    String name = "baeldung";
    Optional<String> nameOptional = Optional.of(name);
    int len = nameOptional.map(String::length).orElse(0);
    assertEquals(8, len);
}

4.2 filter,用于过滤。接收一个函数式接口,当符合接口时,则返回一个Optional对象,否则返回一个空的Optional对象

@Test
public void whenOptionalFilterWorks_thenCorrect() {
    Integer year = 2016;
    Optional<Integer> yearOptional = Optional.of(year);
    boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
    assertTrue(is2016);
    boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
    assertFalse(is2017);
}

 

5. 与Lambda表达式结合使用,优化代码

5.1 条件为true就执行

优化前:

String person = "wo are you";
if(person != null){
System.out.println(person);
}

优化后:

Optional<String> optional = Optional.of("wo are you");
optional.ifPresent(System.out::println);

5.2 条件为true就返回,false返回默认值

优化前:

String person = "wo are you";
if(person != null){
    System.out.println(person);
} else {
    return DEFAULT_VALUE;
}

优化后:

Optional<String> optional = Optional.of("wo are you");
return optional.orElse(DEFAULT_VALUE);

5.3 条件为true就返回,false调用函数生成

优化前:

String person = "wo are you";
if(person != null){
    System.out.println(person);
} else {
    return createPerson();
}

优化后:

Optional<String> optional = Optional.of("wo are you");
return optional.orElseGet(t -> createPerson());

5.4 连环null检查

优化前:

Person person = new Person("Tom");
if(person != null){
    String name = person.getLastName();
    if(name != null){
        return name.toLowerCase();
    } else {
        return null;
    }
} else {
    return null;
}

优化后:

Optional<Person> optional = Optional.ofNullable(new Person("Tom"));
return optional.map(p -> p.getLastName()).map(name -> name.toUpperCase()).orElse(null);

 

 

 

 

 

 

 

posted @ 2019-12-02 20:22  闲人鹤  阅读(2064)  评论(0编辑  收藏  举报