fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.stream.*;
  5. import java.lang.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. static class MyObject {
  12. private String key;
  13. private String value1;
  14. private String value2;
  15.  
  16. MyObject(String key, String value1, String value2) {
  17. this.key = key;
  18. this.value1 = value1;
  19. this.value2 = value2;
  20. }
  21. }
  22.  
  23. static class MyCreatedObject {
  24. private String key;
  25. private List<String> value1List = new ArrayList<>();
  26. private List<String> value2List = new ArrayList<>();
  27.  
  28. MyCreatedObject(MyObject o) {
  29. key = o.key;
  30. value1List.add(o.value1);
  31. value2List.add(o.value2);
  32. }
  33.  
  34. MyCreatedObject merge(MyCreatedObject other) {
  35. key = other.key;
  36. value1List.addAll(other.value1List);
  37. value2List.addAll(other.value2List);
  38. return this;
  39. }
  40.  
  41. @Override
  42. public String toString() {
  43. return String.format("{key=%s, value1List=%s, value2List=%s}",
  44. key, value1List, value2List);
  45. }
  46. }
  47.  
  48. public static void main(String[] args) {
  49. List<MyObject> list = Arrays.asList(
  50. new MyObject("1", "WWW", "EEE"),
  51. new MyObject("1", "WWW", "AAA"),
  52. new MyObject("2", "WWW", "EEE"));
  53.  
  54. Map<String, MyCreatedObject> grouped = list.stream()
  55. .collect(Collectors.toMap(o -> o.key, MyCreatedObject::new, MyCreatedObject::merge));
  56.  
  57. System.out.println(grouped.values());
  58. }
  59. }
Success #stdin #stdout 0.11s 48868KB
stdin
Standard input is empty
stdout
[{key=1, value1List=[WWW, WWW], value2List=[EEE, AAA]}, {key=2, value1List=[WWW], value2List=[EEE]}]