我想要制作一个Java程序,我首先从csv文件读取行,然后将第二列添加到hashmap,第三列是值。Sum HashMap,ArrayList值(来自CSV)
文件中存在重复的product_id(第二列),它们具有不同的值,因此我已将值添加到数组列表中。 现在我必须弄清楚如何从arraylist中实际总结这些值,然后将输出写入csv文件(新建)。
输入CSV(文件仅仅是个开始):
466152;Product_69105;1
466152;Product_69133;6
466152;Product_69214;2
466152;Product_69216;2
466154;Product_01007;1
466154;Product_01083;1
466154;Product_01136;1
466154;Product_01155;1
466154;Product_01488;1
466154;Product_01491;1
466154;Product_01499;2
466154;Product_01513;1
466154;Product_01593;1
466154;Product_01646;1
466154;Product_01656;1
466154;Product_01688;1
466154;Product_01703;1
466154;Product_01770;1
466154;Product_01804;1
466154;Product_01909;1
.....
我现在输出:
Product_03067 [2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 2]
Product_82332 [1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 3, 3, 2, 1, 2, 1, 1, 2, 1, 1]
Product_69594 [1, 1, 1, 1, 1, 1, 2, 2, 1, 1]
Product_82330 [1, 1, 1, 1, 3]
Product_03618 [1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 2, 2, 3, 1, 1, 1, 1,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2]
....
通缉输出:
Product_03067, 20
Product_82332, 29
Product_69594, 12
Product_82330, 7
.....
Public class Tilausmäärä {
Map<String, List<Integer>> tuotteet;
String Tilausrivit = "tilausrivit.csv";
String Tilausrivit_2 = "abc.csv";
public Tilausmäärä() throws FileNotFoundException, IOException {
tuotteet = new HashMap<>();
readTilausrivitFile();
}
public void readTilausrivitFile() throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(new FileReader(Tilausrivit));
String line;
while ((line = in.readLine()) != null) {
String columns[] = line.split(";");
String key = columns[1];
int valueInt;
List<Integer> valueList = null;
try {
valueInt = Integer.parseInt(columns[2]);
} catch (NumberFormatException e) {
System.out.println(e);
continue;
}
if (tuotteet.containsKey(key)) {
valueList = tuotteet.get(key);
} else {
valueList = new ArrayList<>();
tuotteet.put(key, valueList);
}
valueList.add(valueInt);
}
in.close();
}
public static void main(String[] args) {
try {
Tilausmäärä tm = new Tilausmäärä();
for (String k : tm.tuotteet.keySet()) {
System.out.println(k + " " + tm.tuotteet.get(k));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
可以使用一些帮助,所以任何好的想法表示赞赏。
谢谢!
如果目标是,你为什么把他们总结的值列表,而不是直接概括他们,把他们在地图上是什么时候?无论如何,你似乎知道如何建立一个地图,我敢肯定你可以迭代地图的条目(或者至少,你应该能够通过阅读文档来弄清楚),你也应该能够总结一个列表的元素。结合这三件事情,你有你的解决方案。 –
你想要做什么样的输出?另一个CSV文件或只是一个终端打印? – Thecave3
输出也应该是另一个csv文件。 –