How to use Stream in Java to optimize the situation of judging too many conditions in if
This article will explain in detail how Java uses Stream to optimize too many judgment conditions in if. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Using Stream to optimize the situation of too many judgment conditions in if
The new Jdk1.8 feature Stream stream has three such API,anyMatch,allMatch,noneMatch, each of which serves the following purposes:
AnyMatch: returns true if any one of the conditions meets the condition
AllMatch: if all conditions are met, return true
NoneMatch: returns true if none of the conditions is satisfied.
The way they are used is actually very simple:
List list = Arrays.asList ("a", "b", "c", "d", ""); / / trueboolean anyMatch = list.stream (). AnyMatch (s-> StringUtils.isEmpty (s)) if any string judgment is not empty; / / trueboolean allMatch = list.stream () .allMatch (s-> StringUtils.isEmpty (s)) if all string judgments are not empty. / / if no character is judged to be empty, it is trueboolean noneMatch = list.stream () .noneMatch (s-> StringUtils.isEmpty (s))
It can be seen that according to the above three implementation methods, the situation with too many judgment conditions in if can be optimized to some extent, so in which scenario is it more appropriate to use its optimization?
In daily actual development, we may have seen code with a lot of judgment conditions:
If (StringUtils.isEmpty (str1) | | StringUtils.isEmpty (str2) | | StringUtils.isEmpty (str3) | | StringUtils.isEmpty (str4) | | StringUtils.isEmpty (str5) | | StringUtils.isEmpty (str6)) {.}
At this point, you can consider that using the stream stream to optimize, the optimized code is as follows:
If (Stream.of (str1, str2, str3, str4,str5,str6) .anyMatch (s-> StringUtils.isEmpty (s)) {. }
After this optimization, is it more elegant than the conditions piled up in that pile of if?
Of course, this is only for or conditions, and if you encounter 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 optimizing with Stream:
If (Stream.of (str1, str2, str3, str4,str5,str6) .allMatch (s-> StringUtils.isEmpty (s)) {.} about "how Java uses Stream to optimize excessive judgment conditions in if" this article ends here. I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.