How can I use the collect method to collect within a nested ifPresent method?
So far this is what I have:
List result = list.stream()
.findFirst()
.ifPresent(info -> {
info.getMap()
.stream()
.filter( entry -> entry.getKey().equals("test"))
.map(entry::getValue)
.collect(Collectors.toList())
});
You might wanted to do this:
List result = list.stream()
.limit(1)
.flatMap(info -> // <-- removed brace {
info.getMap().stream()
.filter( entry -> entry.getKey().equals("test"))
.map(entry::getValue)
) // <-- removed brace here too
.collect(Collectors.toList());
Let me explain:
.limit(1): limits the stream only to the first element (or returns an empty stream if initial stream is empty)
.flatMap(): maps the stream into a new stream. in this case a new stream consisting of values from Entry#getValue() is returned
.collect(Collectors.toList()): at last the stream of values is collected into a list.
As Olivier Grégoire said in the comments, the following does work too:
List result = list.stream()
.limit(1)
.flatMap(info -> info.getMap().stream())
.filter( entry -> entry.getKey().equals("test"))
.map(entry::getValue)
.collect(Collectors.toList());
Which in my opinion is more readable and clearer indicates what the intents were.
Assuming info.getMap returns a java.util.Map, I don't see why you need the inner stream pipeline at all.
Just use get("test") to obtain the value of the "test" key:
List result =
list.stream()
.map(info -> info.getMap().get("test"))
.filter(Objects::nonNull)
.limit(1)
.collect(Collectors.toList());
P.S., don't use a raw type. You should change the type of the returned list to List<ValueType> where ValueType is the type of values in the info.getMap() Map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With