Skip to content

Instantly share code, notes, and snippets.

@Jayasagar
Created December 17, 2017 15:18
Show Gist options
  • Save Jayasagar/548ecfcdbb6bd5d93b600e4efb5bbb3e to your computer and use it in GitHub Desktop.
Save Jayasagar/548ecfcdbb6bd5d93b600e4efb5bbb3e to your computer and use it in GitHub Desktop.
Map<String, Integer> consumerWithTotalAmount = consumerList
.stream()
.flatMap(consumer -> consumer.getThings()
.stream()
.map(thing -> new AbstractMap.SimpleImmutableEntry<>(consumer.getName(), thing.getCost()))
).collect(Collectors.groupingBy(AbstractMap.SimpleImmutableEntry::getKey,
Collectors.mapping(entry -> entry.getValue(), Collectors.summingInt(value -> value))));
System.out.println(consumerWithTotalAmount);
// Output: {Bob=680, Satti=360, Sri=320, Malli=180}
// In the above code, interesting thing I like is Collectors.summingInt, which is summing device cost.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment