溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java中怎么利用Optional與Stream取代if判空邏輯

發(fā)布時間:2021-07-24 14:46:58 來源:億速云 閱讀:101 作者:Leah 欄目:編程語言

這篇文章給大家介紹Java中怎么利用Optional與Stream取代if判空邏輯,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

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

首先下面代碼中的List放入了很多Person對象,其中有的對象是null的,如果不加校驗調(diào)用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 提供了更加優(yōu)雅的方法:

利用Stream API 中的 filter將隊列中的空對象過濾掉,filter(Objects::nonNull)的意思是,list中的每個元素執(zhí)行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,如果業(yè)務邏輯中要求personList為null時打日志報警,可以用Optional優(yōu)雅的實現(xiàn):

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,則執(zhí)行這2句代碼,返回一個不含元素的List,這樣當personList為null的時候不會報空指針錯誤,并且還打了日志。

關(guān)于Java中怎么利用Optional與Stream取代if判空邏輯就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI