简体   繁体   English

字符串空白(空或空)检查:如果结构与 java 8 可选/过滤器

[英]String blank (empty or null) check : if structure vs java 8 optional/filter

Question : Which approach is better and why问题:哪种方法更好,为什么

1- Using Apache Commons 1- 使用 Apache Commons

if(StringUtils.isNotBlank(str) {
     list.add(str)
}

2- Optional & filter 2-可选和过滤器

Optional.ofNullable(str)
                .filter(s -> StringUtils.isNotBlank(s))
                .ifPresent(result -> list.add(result));

Question : Which approach is better and why问题:哪种方法更好,为什么

The first one , because in the second one you create an unnecessary Optional第一个,因为在第二个中您创建了一个不必要Optional


But I would suggest to use isNotEmpty instead of isNotBlank :但我建议使用isNotEmpty而不是isNotBlank

if(StringUtils.isNotEmpty(str)){
   list.add(str)
}

To know the difference between isNotEmpty and isNotBlank in doc:要了解文档中isNotEmptyisNotBlank之间的区别:

Checks if a CharSequence is not empty ("") and not null .检查 CharSequence 是否不为空("") 并且不是 null

Checks if a CharSequence is not empty (""), not null and not whitespace only .检查 CharSequence 是否不为空(""),不为 null且不为 whitespace only

In your case you ask null or empty, where isNotEmpty is the correct one for your case.在您的情况下,您询问 null 或空,其中isNotEmpty是适合您情况的正确方法。

More of an addendum: my vote went almost immediately to your first option.更多的附录:我的投票几乎立即投给了您的第一个选项。

Why?为什么? Simply: simplicity!简单:简单!

The second snippet is nothing but an if-statement in disguise.第二个片段只不过是一个变相的 if 语句。 And that disguise comes with plenty of overhead.这种伪装会带来大量开销。

Your human readers have to look at all the characters, then they need to dissect the complex statement, then they need to know how Optional works, and what the given code actually does.您的人类读者必须查看所有字符,然后他们需要剖析复杂的语句,然后他们需要知道Optional 是如何工作的,以及给定代码的实际作用。

So, besides the subtle performance differences, as outlined in the other answer: the real answer: you should ask the people in your team.因此,除了细微的性能差异,正如另一个答案中所述:真正的答案:您应该询问团队中的人员。

If they are all used to Optional usage like here, and they do that all day long, then, maybe, the better style is option 2. Because that is what all of you do, day in day out.如果他们都习惯了像这里这样的Optional用法,并且他们整天都这样做,那么,也许更好的风格是选项 2。因为这就是你们所有人每天都在做的事情。 But if not, as said: I recommend to go with the simpler lines of code, that can be understood by anybody who knows basic java.但如果不是,如前所述:我建议 go 使用更简单的代码行,任何了解基本 java 的人都可以理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM