How to convert an Optional into a Stream?

后端 未结 6 1578
孤独总比滥情好
孤独总比滥情好 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:13

    In Java-9 the missing stream() method is added, so this code works:

    Stream<String> texts = optional.stream();
    

    See JDK-8050820. Download Java-9 here.

    0 讨论(0)
  • 2020-12-05 04:17

    If restricted with Java-8, you can do this:

    Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);
    
    0 讨论(0)
  • 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<String> flintstones = new ArrayList<String>(){{
            add("Fred");
            add("Wilma");
            add("Pebbles");
        }};
    
        final List<String> another = Optional.ofNullable(flintstones)
                .map(Stream::of)
                .orElseGet(Stream::empty)
                .toList();
    

    This example just makes a copy of the list.

    0 讨论(0)
  • 2020-12-05 04:27

    You can do:

    Stream<String> texts = optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
    
    0 讨论(0)
  • 2020-12-05 04:28

    I can recommend Guava's Streams.stream(optional) method if you are not on Java 9. A simple example:

    Streams.stream(Optional.of("Hello"))
    

    Also possible to static import Streams.stream, so you can just write

    stream(Optional.of("Hello"))
    
    0 讨论(0)
  • 2020-12-05 04:30

    A nice library from one of my ex collegues is Streamify. A lot of collectors, creating streams from practicly everything.

    https://github.com/sourcy/streamify

    Creating a stream form an optional in streamify:

    Streamify.stream(optional)
    
    0 讨论(0)
提交回复
热议问题