Skip to content

Instantly share code, notes, and snippets.

@Jayasagar
Created December 17, 2017 15:16
Show Gist options
  • Save Jayasagar/8b333e3ab751974216ec81ac4f6bbf40 to your computer and use it in GitHub Desktop.
Save Jayasagar/8b333e3ab751974216ec81ac4f6bbf40 to your computer and use it in GitHub Desktop.
// How to loop over nested collections referring to parent elements?
List<Consumer> allConsumersWhoHasHealthDevice = consumerList
.stream()
.flatMap(consumer -> consumer.getThings().stream()
.filter(thing -> thing.isRunning() && Type.HEALTH == thing.getType())
// This is cool!!!
.map(thing -> new AbstractMap.SimpleImmutableEntry<>(consumer, thing))
)
.map(entry -> entry.getKey())
.collect(Collectors.toList());
System.out.println(allConsumersWhoHasHealthDevice);
// Output: [Consumer(name=Sri, city=Hyd), Consumer(name=Bob, city=Berlin)]
// In the above code, very interesting point is, we hold the outer/parent element 'Consumer'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment