delita delita - 3 years ago 114
Java Question

lambda collecting within a ifPresent

how can use the collectors function 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())
});

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download