在Java 8中,转换Optional< String> Optional.empty中的空字符串 [英] In Java 8, transform Optional<String> of an empty String in Optional.empty

查看:942
本文介绍了在Java 8中,转换Optional< String> Optional.empty中的空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个String我需要获得一个Optional,如果String为null或为空,则结果为Optional.empty。
我可以这样做:

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:

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.

推荐答案

您可以使用过滤器:

Optional<String> ostr = Optional.ofNullable(ppo).filter(s -> !s.isEmpty());

如果 ppo 那将返回空的可选项为空或空。

That will return an empty Optional if ppo is null or empty.

这篇关于在Java 8中,转换Optional&lt; String&gt; Optional.empty中的空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆