Skip to content

Instantly share code, notes, and snippets.

@beall49
Last active March 4, 2023 03:10
Show Gist options
  • Save beall49/8f85412f018718e64e09198b806461d1 to your computer and use it in GitHub Desktop.
Save beall49/8f85412f018718e64e09198b806461d1 to your computer and use it in GitHub Desktop.
Group and Sum By Id
private Map<Integer, Integer> getGroupsById() {
List<IdValue> values = Lists.newArrayList(
new IdValue(1, 2),
new IdValue(1, 6),
new IdValue(3, 1),
new IdValue(3, 3),
new IdValue(5, 3),
new IdValue(5, 10)
);
Map<Integer, Integer> collect = values.stream()
.collect(Collectors.groupingBy(IdValue::getId, Collectors.toList()))
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> entry.getValue()
.stream()
.mapToInt(IdValue::getValue)
.sum()
)
);
collect.forEach((key, value) -> log.info("group ==> {} {} ", key, value));
return collect;
}
private static class IdValue {
private int id;
private int value;
public IdValue(int id, int value) {
this.id = id;
this.value = value;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment