Skip to content

Instantly share code, notes, and snippets.

@Jayasagar
Created December 17, 2017 15:17
Show Gist options
  • Save Jayasagar/329e9f1bac09c98d18a8af003c03f59c to your computer and use it in GitHub Desktop.
Save Jayasagar/329e9f1bac09c98d18a8af003c03f59c to your computer and use it in GitHub Desktop.
Map<Type, Set<String>> allUsersByDeviceType = consumerList
.stream()
.flatMap(consumer -> consumer.getThings()
.stream()
.map(thing -> new AbstractMap.SimpleImmutableEntry<>(thing.getType(), consumer.getName()))
).collect(Collectors.groupingBy(AbstractMap.SimpleImmutableEntry::getKey,
Collectors.mapping(entry -> entry.getValue(), Collectors.toSet()))
);
System.out.println(allUsersByDeviceType);
//Output: {HOME=[Satti, Bob, Sri, Malli], HEALTH=[Bob, Sri], FIELD=[Satti, Bob]}
// In the above code, interesting thing I like is Collectors.mapping, which is helping to collect map values as set.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment