问题描述
所以我一直在使用Guava的Optional一段时间了,我转到Java 8所以我想使用它的Optional类,但它没有我最喜欢的方法来自Guava,asSet()。有没有办法用Java 8 Optional来做到这一点,我没有看到。我喜欢能够将可选项视为一个集合,所以我可以这样做:
So I have been using Guava's Optional for a while now, and I moving to Java 8 so I wanted to use it's Optional class, but it doesn't have my favorite method from Guava, asSet(). Is there a way to do this with the Java 8 Optional that I am not seeing. I love being able to treat optional as a collection so I can do this:
for( final User u : getUserOptional().asSet() ) {
return u.isPermitted(getPermissionRequired());
}
在某些情况下,无需额外的变量。
In some cases avoids the need for an additional variable.
IE
Optional<User> optUser = getUserOptional();
if ( optUser.isPresent() ) {
return optUser.get().isPermitted(getPermissionRequired());
}
是否有一种简单的方法可以在Java 8的Optional中复制Guava样式?
Is there an easy way to replicate the Guava style in Java 8's Optional?
谢谢
推荐答案
有一种转换<$的简单方法c $ c>可选到集合
。它就像可选
的任何其他转换一样:
There is a simple way of converting an Optional
into a Set
. It works just like any other conversion of an Optional
:
给定可选< T> ; o
你可以调用
o.map(Collections::singleton).orElse(Collections.emptySet())
获得设置< T>
。如果您不喜欢在每种情况下调用 Collections.emptySet()
的想法,您可以将其转换为惰性评估:
to get a Set<T>
. If you don’t like the idea of Collections.emptySet()
being called in every case you can turn it into a lazy evaluation:
o.map(Collections::singleton).orElseGet(Collections::emptySet)
然而,这种方法太过微不足道,无法产生性能差异。所以这只是编码风格的问题。
however, the method is too trivial to make a performance difference. So it’s just a matter of coding style.
你也可以用它来按预期迭代:
You can also use it to iterate like intended:
for(T t: o.map(Collections::singleton).orElse(Collections.emptySet()))
// do something with t, may include a return statement
这篇关于Java 8可选asSet()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!