我有 3 个类:
- Calculation class (includes FinalPrice() method which is return with a double value)
- 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)
- 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());
我需要一个列表来存储 Contract 对象并对键进行分组(即 b.getType(a) )并对它们的值求和(即 calc.FinalPrice() ),例如
输入(例如):
list.add("AB", 5); list.add("AC", 8); list.add("AB", 12);
我想得到这样的输出:
"AB" : 17 "AC" : 8
谁能帮帮我?
最佳答案
在 Java 8 中,
entries.stream().collect(Collectors.groupingBy(
entry -> entry.getKey(),
Collectors.summingInt(entry -> entry.getValue())));
关于数组列表中的Java分组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35733922/