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?

2
  • 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 Commented Mar 1, 2016 at 21:33
  • 1
    This is a duplicate of: stackoverflow.com/questions/23848129/… Commented Mar 1, 2016 at 22:28

1 Answer 1

1

In Java 8,

 entries.stream().collect(Collectors.groupingBy(
      entry -> entry.getKey(),
      Collectors.summingInt(entry -> entry.getValue())));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.