2013-07-03 22 views
5

我有一個方法,採用參數Collection<Foo> foos,它可能是NULL。我想以輸入的本地副本作爲ImmutableSet。現在我的代碼看起來像這樣:乾淨番石榴的方式來處理可能爲null的收集

if (foos == null) 
{ 
    this.foos = ImmutableSet.of(); 
} 
else 
{ 
    this.foos = ImmutableSet.copyOf(foos); 
} 

有沒有更乾淨的方法來做到這一點?如果foos是一個簡單的參數,我可以做一些像Objects.firstNonNull(foos, Optional.of())但我不確定是否有類似的東西處理集合。

回答

13

我不明白爲什麼你不能使用Objects.firstNonNull

this.foos = ImmutableSet.copyOf(Objects.firstNonNull(foos, ImmutableSet.of())); 

可以節省一些打字靜態導入,如果那是你的事:

import static com.google.common.collect.ImmutableSet.copyOf; 
import static com.google.common.collect.ImmutableSet.of; 
// snip... 
this.foos = copyOf(Objects.firstNonNull(foos, of())); 
+5

+1可能值得指出的是'copyOf'足夠聰明,只要它是一個'ImmutableSet'就可以返回輸入。 –

+1

@PaulBellora我相信你剛剛做到了。 ':)' –

+3

另外'ImmutableSet。 ()'可能是不必要的。 –

7

一個Collection就像任何其他的引用,所以你可以這樣做:

ImmutableSet.copyOf(Optional.fromNullable(foos).or(ImmutableSet.of())); 

但是,這正在成爲相當少數寫。更簡單:

foos == null ? ImmutableSet.of() : ImmutableSet.copyOf(foos); 
+0

第二個例子的優點是不需要創建一個空集合。即使傳遞的集合不爲null,MattBall的答案也會始終創建空的「集合」。 –

+5

@JohnB'ImmutableSet.of()'[返回一個單例](http://docs.guava-libraries.googlecode.com/git/javadoc/src-html/com/google/common/collect/ImmutableSet.html# line.83)。 –

+0

啊,當然是的!乾杯。 –