Java 8可选 [英] Java 8 Optional

查看:88
本文介绍了Java 8可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个特定的对象大小是否大于0.如果它大于0,那么我想创建一个可选对象,如果没有,那么我想返回一个Optional空。这是java代码的长版本:

I want to check if a particular object size is greater than 0. If it is greater than 0 then I want to create an optional object, if not then I want to return an Optional empty. This is the long version of the java code:

if(fooA.size>0) {
    return Optional.of(new Foo());
} else {
    return Optional.empty();
}

有没有办法使用java 8的可选库将其压缩成一行?

Is there any way to compact this into one line using java 8's optional library?

推荐答案


有没有办法使用java 8的可选库将其压缩成一行?

Is there any way to compact this into one line using java 8's optional library?

如果你坚持使用Optional类,你可以使用 Optional.ofNullable() 并且只是通过 null 如果条件不满足:

If you insist on using the Optional class, you could use Optional.ofNullable() and just pass it null if the condition isn't met:

return Optional.ofNullable(fooA.size > 0 ? new Foo() : null);

但请注意( Holger 正确陈述)与用三元替换if / else语句相比,没有任何显着的 1 优势(如 tobias_k 和Holger都在他们的 评论):

Note, however (as Holger correctly states) that using the Optional class doesn't give you any significant1 advantage over just replacing your if/else statement with a ternary one (as tobias_k and Holger have both done in their comments):

return fooA.size > 0 ? Optional.of(new Foo()) : Optional.empty();

1 第一行稍短,我通常认为是优势,但在这种情况下绝对无关紧要,因为长度差异可以忽略不计。

1 The first line is a little shorter, which I usually consider an advantage, but an absolutely insignificant one in this case, as the length difference is negligible.

这篇关于Java 8可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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