首頁  >  文章  >  Java  >  Java如何使用Stream最佳化if中判斷條件過多狀況

Java如何使用Stream最佳化if中判斷條件過多狀況

王林
王林轉載
2023-05-05 10:40:062282瀏覽

使用Stream優化if中判斷條件過多情況

Jdk1.8新特性Stream流有三個這樣API,anyMatch,allMatch,noneMatch,各自的作用如下:

  • #anyMatch:判斷條件裡任一個滿足條件,則回傳true;

  • allMatch:判斷條件裡所有都符合條件,則回傳true;

  • noneMatch:判斷條件裡所有都不符合條件,則回傳true;

#它們的使用方式其實很簡單:

List<String> list = Arrays.asList("a", "b", "c","d", "");
//任意一个字符串判断不为空则为true
boolean anyMatch = list.stream().anyMatch( s->StringUtils.isEmpty(s));
//所有字符串判断都不为空则为true
boolean allMatch = list.stream().allMatch( s->StringUtils.isEmpty(s));
//没有一个字符判断为空则为true
boolean noneMatch = list.stream().noneMatch( s->StringUtils.isEmpty(s));

可見,根據以上三種實現方式,可以在某種程度上優化if裡判斷條件過多的情況,那麼,在哪個場景裡比較適合利用其優化呢?

在日常實際開發當中,我們可能會看到過這樣存在很多判斷條件的程式碼:

 if(StringUtils.isEmpty(str1) || StringUtils.isEmpty(str2) ||
    StringUtils.isEmpty(str3) || StringUtils.isEmpty(str4) ||
    StringUtils.isEmpty(str5) || StringUtils.isEmpty(str6)
   ){
 .....
}

這時,就可以考慮到,使用stream流來優化,優化後的程式碼如下:

if(Stream.of(str1, str2, str3, str4,str5,str6).anyMatch(s->StringUtils.isEmpty(s))){
 .....
 }

這樣優化後,是不是就比那堆if裡堆積到一塊的條件更為優雅了?

當然,這只是針對或條件的,若是遇到與條件時,同樣可以用Stream來優化,例如:

if(StringUtils.isEmpty(str1) && StringUtils.isEmpty(str2) &&
   StringUtils.isEmpty(str3) && StringUtils.isEmpty(str4) &&
   StringUtils.isEmpty(str5) && StringUtils.isEmpty(str6)
){
   .....
}

使用Stream優化後:

if(Stream.of(str1, str2, str3, str4,str5,str6).allMatch(s->StringUtils.isEmpty(s))){
  .....
}

以上是Java如何使用Stream最佳化if中判斷條件過多狀況的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除