I get a map from a service not under my control that might be null and want to process it, let's say, filter, map and reduce to a single element I need.
Question: is there a "link" from Optional to Stream?
I tried (among other things):
return Optional.ofNullable(getMap())
.map(Map::entrySet) // gets the entryset
.map(Stream::of)
.orElseGet(Stream::empty)
// i would then like to continue with
.filter(e -> e.getKey().startsWith("f")
.map(Entry::getValue)
.findFirst();
but then I get not Stream<Entry>
but Stream<Set<Entry>>
... is there a way to somehow flatMap a collection or map out of an Optional?
Note: I am interested in a fluent, pure stream/optional approach here. It works of course when I save the map to local var first and make sure it is not null.
Your mistake is in this line:
.map(Stream::of)
The of
function takes a single parameter (or a vararg parameter), and returns a stream with only that element. You will therefore get a Stream<Set<Map.Entry>>
. Instead, you should call the stream method on the entryset, like this:
.map(Set::stream)