java - lambda collecting within a ifPresent -


how can use collectors function collect within nested ifpresent method? far 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 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     .collect(collectors.tolist()); 

let me explain:

.limit(1): limits stream first element (or returns empty stream if initial stream empty)

.flatmap(): maps stream new stream. in case new stream consisting of values entry#getvalue() returned

.collect(collectors.tolist()): @ last stream of values collected list.

as olivier grégoire said in comments, following 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 opinion more readable , clearer indicates intents were.


Comments

Popular posts from this blog

javascript - Replicate keyboard event with html button -

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Web audio api 5.1 surround example not working in firefox -