在 Java 8 中,在 Optional.empty 中转换空字符串的 Optional<String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28322464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java 8, transform Optional<String> of an empty String in Optional.empty
提问by Germán Bouzas
Given a String I need to get an Optional, whereby if the String is null or empty the result would be Optional.empty. I can do it this way:
给定一个字符串,我需要获得一个 Optional,如果字符串为 null 或为空,结果将是 Optional.empty。我可以这样做:
String ppo = "";
Optional<String> ostr = Optional.ofNullable(ppo);
if (ostr.isPresent() && ostr.get().isEmpty()) {
ostr = Optional.empty();
}
But surely there must be a more elegant way.
但肯定必须有更优雅的方式。
采纳答案by assylias
You could use a filter:
您可以使用过滤器:
Optional<String> ostr = Optional.ofNullable(ppo).filter(s -> !s.isEmpty());
That will return an empty Optional if ppo
is null or empty.
如果ppo
为 null 或为空,则将返回一个空的 Optional 。
回答by Jon Skeet
How about:
怎么样:
Optional<String> ostr = ppo == null || ppo.isEmpty()
? Optional.empty()
: Optional.of(ppo);
You can put that in a utility method if you need it often, of course. I see no benefit in creating an Optional
with an empty string, only to then ignore it.
当然,如果你经常需要它,你可以把它放在一个实用方法中。我认为创建一个Optional
空字符串没有任何好处,然后忽略它。
回答by Eran
You can use map :
您可以使用地图:
String ppo="";
Optional<String> ostr = Optional.ofNullable(ppo)
.map(s -> s.isEmpty()?null:s);
System.out.println(ostr.isPresent()); // prints false
回答by Feeco
With Apache Commons:
使用 Apache Commons:
.filter(StringUtils::isNotEmpty)
回答by Gonzalo Vallejos Bobadilla
If you use Guava, you can just do:
如果你使用番石榴,你可以这样做:
Optional<String> ostr = Optional.ofNullable(Strings.emptyToNull(ppo));
回答by Michael Barnwell
Java 11 answer:
Java 11 答案:
var optionalString = Optional.ofNullable(str).filter(Predicate.not(String::isBlank));
String::isBlank
deals with a broader range of 'empty' characters.
String::isBlank
处理更广泛的“空”字符。