Last active
March 4, 2023 03:10
-
-
Save beall49/8f85412f018718e64e09198b806461d1 to your computer and use it in GitHub Desktop.
Group and Sum By Id
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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