How to convert an Optional into a Stream?

后端 未结 6 1612
孤独总比滥情好
孤独总比滥情好 2020-12-05 03:56

I want to prepend a stream with an Optional. Since Stream.concat can only concatinate Streams I have this question:

How do I convert an Optional

6条回答
  •  醉酒成梦
    2020-12-05 04:24

    If you're on an older version of Java (lookin' at you, Android) and are using the aNNiMON Lightweight Stream API, you can do something along the lines of the following:

        final List flintstones = new ArrayList(){{
            add("Fred");
            add("Wilma");
            add("Pebbles");
        }};
    
        final List another = Optional.ofNullable(flintstones)
                .map(Stream::of)
                .orElseGet(Stream::empty)
                .toList();
    

    This example just makes a copy of the list.

提交回复
热议问题