Using a stream based on the contents of an optional <Map>

I get a card from a service that is not under my control, which can be zero and wants to process it, say, filter, map and reduce to one element that I need.

Question: Is there a "Optional for Stream" link?

I tried (by the way):

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 collections or maps from optional?

Note: I'm interested in a free, clean thread / optional approach. This works, of course, when I first save the map in a local var and make sure that it is not null.

+5
source share
2 answers

Your error on this line:

 .map(Stream::of) 

The of function takes one parameter (or the vararg parameter) and returns a stream with only this element. So you get Stream<Set<Map.Entry>> . Instead, you should call the stream method on the input, for example:

 .map(Set::stream) 
+8
source

I think I'm going to answer the question.

  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(); 

I am sick, very sick when I saw the code above. Is it really important for you to write code freely and not write simple code? First of all, as @Didier L mentioned in the comments, this is the wrong way to use Optional . Secondly, code is so hard to read, isn't it? if you write it with a local variable definition:

 Map<String, Integer> map = getMap(); return map == null ? Optional.<Integer> empty() : map.entrySet().stream() .filter(e -> e.getKey().startsWith("f")).map(Entry::getValue).findFirst(); 

Isn't that clear? Or you can do it with StreamEx if you cannot overcome without using a free approach:

 StreamEx.ofNullable(getMap()) .flatMapToEntry(Function.identity()) .filterKeys(k -> k.startsWith("f")).values().findFirst(); 

Or my AbacusUtil library

 EntryStream.of(getMap()).filterByKey(k -> k.startsWith("f")).values().first(); 

Always try to find the best approach if everything gets stuck.

0
source

Source: https://habr.com/ru/post/1268869/


All Articles