fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.stream.Collectors;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static class Obj {
  12. private int value;
  13. private String category;
  14.  
  15. public Obj(int value, String category) {
  16. this.value = value;
  17. this.category = category;
  18. }
  19.  
  20. public int getValue() { return value; }
  21. public void setValue(int value) { this.value = value; }
  22.  
  23. public String getCategory() { return category; };
  24. public void setCategory(String category) {this.category = category; };
  25.  
  26.  
  27. @Override
  28. public String toString() {
  29. return category + ":" + value;
  30. }
  31. }
  32.  
  33. public static void main (String[] args) throws java.lang.Exception
  34. {
  35. List<Obj> list = new ArrayList<>();
  36. list.add(new Obj(500, "GROCERY"));
  37. list.add(new Obj(300, "GROCERY"));
  38. list.add(new Obj(100, "FUEL"));
  39. list.add(new Obj(300, "SMALL APPLIANCE REPAIR"));
  40. list.add(new Obj(200, "FUEL"));
  41.  
  42. List<Obj> values = list.stream().collect(
  43. Collectors.groupingBy(Obj::getCategory, Collectors.reducing((a, b) -> new Obj(a.getValue() + b.getValue(), a.getCategory())))
  44. ).values().stream().map(Optional::get).collect(Collectors.toList());
  45.  
  46. List<Obj> values2 = list.stream().sorted((o1, o2) -> o1.getCategory().compareTo(o2.getCategory()))
  47. .collect(LinkedList<Obj>::new, (ll, obj) -> {
  48. Obj last = null;
  49. if(!ll.isEmpty()) {
  50. last = ll.getLast();
  51. }
  52.  
  53. if (last == null || !last.getCategory().equals(obj.getCategory())) {
  54. ll.add(new Obj(obj.getValue(), obj.getCategory())); //deep copy here
  55. } else {
  56. last.setValue(last.getValue() + obj.getValue());
  57. }
  58. },
  59. (list1, list2) -> {
  60. throw new RuntimeException("parallel evaluation not supported");
  61. });
  62.  
  63.  
  64. System.out.println(values);
  65. System.out.println(values2);
  66. // your code goes here
  67. }
  68. }
Success #stdin #stdout 0.23s 320960KB
stdin
Standard input is empty
stdout
[SMALL APPLIANCE REPAIR:300, FUEL:300, GROCERY:800]
[FUEL:300, GROCERY:800, SMALL APPLIANCE REPAIR:300]