2

I have 3 classes:

  1. Calculation class (includes FinalPrice() method which is return with a double value)
  2. File Reader class (Load CSV file, split data into an array and return with the first element of the array, which is a String. Includes getType() method)
  3. Contract class(only contains a constructor)

File a = new File("D:\\...\\contract.csv"); Calculation1 calc = new Calculation1(a); File_Reader1 b = new File_Reader1(); Contract c = new Contract(b.getType(a),calc.FinalPrice());

I need a list to store Contract objects and grouping the keys (which is b.getType(a) ) and sum their values (which is calc.FinalPrice() ), like

Input (for example):

list.add("AB", 5); list.add("AC", 8); list.add("AB", 12);

I would like to get an output like this:

"AB" : 17 "AC" : 8

Can anyone help me?

  • you could iterate your ArrayList or Map or whatever and in a second list aggregate the value (check with contains() if a key is already in the second list or not) - this is certainly not very performant, but it should work. Depends on how large your list / map should be – Valentin Kuhn Mar 01 '16 at 21:33
  • 1
    This is a duplicate of: http://stackoverflow.com/questions/23848129/is-there-an-aggregateby-method-in-the-stream-java-8-api – Tunaki Mar 01 '16 at 22:28

1 Answers1

1

In Java 8,

 entries.stream().collect(Collectors.groupingBy(
      entry -> entry.getKey(),
      Collectors.summingInt(entry -> entry.getValue())));
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413