Home  >  Article  >  Java  >  How to use Stream in Java to optimize the judgment of too many conditions in if

How to use Stream in Java to optimize the judgment of too many conditions in if

王林
王林forward
2023-05-05 10:40:062350browse

Use Stream to optimize the condition of too many judgment conditions in if

Jdk1.8 new feature Stream stream has three such APIs, anyMatch, allMatch, noneMatch, their respective functions are as follows:

  • anyMatch: if any one of the conditions satisfies the condition, then true is returned;

  • allMatch: if all of the conditions satisfy the condition, true is returned;

  • noneMatch: if none of the judgment conditions meet the conditions, then return true;

The way they are used is actually very simple:

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));

It can be seen, According to the above three implementation methods, the situation of too many judgment conditions in if can be optimized to a certain extent. So, in which scenario is it more suitable to use its optimization?

In daily actual development, we may have seen codes like this with many judgment conditions:

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

At this time, you can consider using stream flow to optimize, and the optimized The code is as follows:

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

After optimization like this, is it more elegant than the conditions piled together in a bunch of ifs?

Of course, this is only for or conditions. If you encounter and conditions, you can also use Stream to optimize, for example:

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

After using Stream to optimize:

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

The above is the detailed content of How to use Stream in Java to optimize the judgment of too many conditions in if. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete
Previous article:What are Java assertionsNext article:What are Java assertions