2016-03-02 28 views
8

使用Java Stream時,映射後可能會出現空值。目前,當這些價值需要被省略了,我用:在流中篩選空項目

.stream() 
.<other operations...> 
.filter(element -> element != null) 
.<other operations...> 

對於更實用的風格一個小的輔助方法,飛快地寫着:

public static <T> boolean nonNull(T entity) { 
    return entity != null; 
} 

這樣就可以使用方法引用來代替:

.stream() 
.<other operations...> 
.filter(Elements::nonNull) 
.<other operations...> 

我找不到這樣一個jdk方法,即使我懷疑他們已經包含了一個。這裏有不同的方法嗎?還是因爲某種原因忽略了這個?

+9

'e - > e!= null'有什麼問題? – immibis

+2

本身沒有什麼,但我更喜歡在只使用方法引用的管道中出現這種情況時的方法引用。這感覺就像一個組合破壞者。 –

+1

相關:[Objects :: nonNull和x - > x!= null?是否有區別?](https://stackoverflow.com/questions/25435056/is-there-any-difference-between-objectsnonnull-and- xx-null) –

回答

27

您可以使用Objects::nonNull從Java8 SDK:

.stream() 
.<other operations...> 
.filter(Objects::nonNull) 
.<other operations...> 
+0

不能相信我忽略了那一個! –

+0

@BorisvanKatwijk檢查整個Objects類,有一些很酷的東西:-) –

2

可以使用Objects::nonNull

返回true如果提供的參考是非空,否則返回 假。

.stream() 
.<other operations...> 
.filter(Objects::nonNull) 
.<other operations...>