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

后端 未结 6 1675
隐瞒了意图╮
隐瞒了意图╮ 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:35

    Personally I consider null deprecated and use Optional wherever possible despite the (tiny) performance overhead. So I use the interface from Stuart Marks with an implementation based on gdejohn, i.e.

    @SuppressWarnings("unchecked")
    static  Stream nullableCollectionToStream(Collection coll)
    {
        return (Stream) Optional.ofNullable(coll)
                               .map(Collection::stream)
                               .orElseGet(Stream::empty);
    }
    

提交回复
热议问题