fork download
  1.  
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.stream.Collectors;
  5.  
  6. class Mainlove {
  7.  
  8. private String key;
  9. private int v1;
  10. private int v2;
  11.  
  12. public Mainlove(String key, int v1, int v2) {
  13. setKey(key);
  14. setV1(v1);
  15. setV2(v2);
  16. }
  17.  
  18. public String getKey() {
  19. return key;
  20. }
  21.  
  22. public void setKey(String key) {
  23. this.key = key;
  24. }
  25.  
  26. public int getV1() {
  27. return v1;
  28. }
  29.  
  30. public void setV1(int v1) {
  31. this.v1 = v1;
  32. }
  33.  
  34. public int getV2() {
  35. return v2;
  36. }
  37.  
  38. public void setV2(int v2) {
  39. this.v2 = v2;
  40. }
  41.  
  42. public String toString() {
  43. return String.format("%s %s %s", getKey(), getV1(), getV2());
  44. }
  45.  
  46. public static void main(String[] args) {
  47. List<Mainlove> list = new ArrayList<>();
  48. list.add(new Mainlove("a", 2, 3));
  49. list.add(new Mainlove("b", 1, 1));
  50. list.add(new Mainlove("a", 1, 1));
  51. list.add(new Mainlove("c", 1, 1));
  52. list.add(new Mainlove("b", 1, 1));
  53.  
  54. // https://h...content-available-to-author-only...i.com/article/1507601898720
  55. // key 进行分组,分组的同时 把 value1 和 value2 求和
  56. // 最后需要的结果是 [a,3,4] [b,2,2] [c,1,1]
  57.  
  58.  
  59. List<Mainlove> cml = new ArrayList<>();
  60.  
  61. list.stream().collect(Collectors.groupingBy(Mainlove::getKey)).forEach((k, v)-> cml.add(new Mainlove(k, v.stream().mapToInt(Mainlove::getV1).sum(), v.stream().mapToInt(Mainlove::getV2).sum())));
  62.  
  63. cml.forEach(System.out::println);
  64.  
  65.  
  66. }
  67. }
  68.  
Success #stdin #stdout 0.21s 2841600KB
stdin
Standard input is empty
stdout
a 3 4
b 2 2
c 1 1