如何将可选的 < T > 转换为流 < T > ?

我想用一个可选项预置一个流。因为 Stream.concat只能连接流,所以我有这样一个问题:

如何将可选的 < T > 转换为流 < T > ?

例如:

Optional<String> optional = Optional.of("Hello");
Stream<String> texts = optional.stream(); // not working
24789 次浏览

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

Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);

You can do:

Stream<String> texts = optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();

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.

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"))

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.

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)

It can depend of how you want to convert empty optional to stream element. If you want to interpret it as "nothing" (or "no element"):

Stream<String> texts = optional.stream(); // since JDK 9
Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty); // JDK 8

But if you want to interpret it as null:

Stream<String> texts = Stream.of(optional.oreElse(null));