How to best create a Java 8 stream from a nullable object?

后端 未结 6 1685
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 02:01

What is the best/idiomatic way of doing a null check before getting a stream?

I have method that is receiving a List that might be null. So I can\'t jus

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 02:25

    Java 8:

    Optional.ofNullable(collection)
        .stream()
        .flatMap(Collection::stream)
    

    Java 9:

    Stream.ofNullable(collection)
        .flatMap(Collection::stream)
    

    Apache Commons Collections 4:

    import org.apache.commons.collections4.CollectionUtils;
    CollectionUtils.emptyIfNull(collection)
        .stream()
    

提交回复
热议问题