Filter Null Values from a List with Java8 Lambda

A common task with Java streams is to clean up the input data so later steps can work without thinking too hard. Likely the #1 most common cleanup step is to remove nulls from a Collection.

Streams make it easy:

myCollection.stream()
  .filter(Objects::nonNull)
  .do.what.you.need

Enter fullscreen mode Exit fullscreen mode

Compare with the classic approaches:

while(myCollection.remove(null));
// do what you need, but you better not need that original list, because it's gone...
myCollection.removeAll(Collections.singleton(null));
// do what you need, but you better not need that original list, because it's gone...

Enter fullscreen mode Exit fullscreen mode

Like the stream approach, these are short and sweet, but unlike the stream approach they modify the original list. The first example is also pretty slow.

I like the stream approach because I can chain additional tasks after the filter task, including map. sorted, reduce and more!. I find the traditional imperative iterative approach to be not only wordier, but conceptually harder to follow.

原文链接:Filter Null Values from a List with Java8 Lambda

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容