Java使用Optional與Stream來取代if判空邏輯(JDK8以上)

  • 2019 年 10 月 3 日
  • 筆記

Java使用Optional與Stream來取代if判空邏輯(JDK8以上)

通過本文你可以用非常簡短的代碼替代業務邏輯中的判null校驗,並且很容易的在出現空指針的時候進行打日誌或其他操作。

註:如果對Java8新特性中的lambda表達式與Stream不熟悉的可以去補一下基礎,了解概念。

首先下面代碼中的List放入了很多Person對象,其中有的對象是null的,如果不加校驗調用Person的getXXX()方法肯定會報空指針錯誤,一般我們採取的方案就是加上if判斷:

public class DemoUtils {        public static void main(String[] args) {          List<Person> personList = new ArrayList<>();          personList.add(new Person());          personList.add(null);          personList.add(new Person("小明",10));          personList.add(new Person("小紅",12));            for (Person person : personList) {          //if判空邏輯              if (person != null) {                  System.out.println(person.getName());                  System.out.println(person.getAge());              }          }      }        static class Person {          private String name;          private int age;            public Person() {          }            public Person(String name, int age) {              this.name = name;              this.age = age;          }            public String getName() {              return name;          }          public void setName(String name) {              this.name = name;          }          public int getAge() {              return age;          }          public void setAge(int age) {              this.age = age;          }      }  }

其實,Java新特性Stream API 與 Optional 提供了更加優雅的方法:

利用Stream API 中的 filter將隊列中的空對象過濾掉,filter(Objects::nonNull)的意思是,list中的每個元素執行Objects的nonNull()方法,返回false的元素被過濾掉,保留返回true的元素。

 public static void main(String[] args) {          List<Person> personList = new ArrayList<>();          personList.add(new Person());          personList.add(null);          personList.add(new Person("小明",10));          personList.add(new Person("小紅",12));            personList.stream().filter(Objects::nonNull).forEach(person->{              System.out.println(person.getName());              System.out.println(person.getAge());          });      }

示例中的personList本身也可能會null,如果業務邏輯中要求personList為null時打日誌報警,可以用Optional優雅的實現:

public static void main(String[] args) {      List<Person> personList = new ArrayList<>();      personList.add(new Person());      personList.add(null);      personList.add(new Person("小明", 10));      personList.add(new Person("小紅", 12));        Optional.ofNullable(personList).orElseGet(() -> {          System.out.println("personList為null!");          return new ArrayList<>();      }).stream().filter(Objects::nonNull).forEach(person -> {          System.out.println(person.getName());          System.out.println(person.getAge());      });  }

代碼中的

orElseGet(() -> {      //代替log      System.out.println("personList為null!");      return new ArrayList<>();  })

表示如果personList為null,則執行這2句代碼,返回一個不含元素的List,這樣當personList為null的時候不會報空指針錯誤,並且還打了日誌。