我知道它被问了一百次,答案总是一样的,你不能在 HashMap 中使用多个重复值。 但是让我们开始讨论这个问题。我有一个导入文件,导入文件包含有关 CustomerID、ProductID 和售出单位(其基本收据格式)的信息。 我想要做的是获取导入,将其放入 map 中,并能够引用它。
Map<integer,DoubleSales> hashmap = new HashMap <integer,DoubleSales>
try {
Scanner dataFile = new Scanner 9new File ("./salesData.csv"));
dataFile.nextLine();
while(dataFile.hasNextLine()){
String[] lineValues = line.split (",");
Integer CustomerID = Integer.parseInt(lineValues[0]);
Integer ProductID = Integer.parseInt(lineValues[1]);
integer Units = Integer.parseInt(lineValues[2]);
DoubleSales sales = new DoubleSales(CustomerID,ProductID,Units);
ProductData.put(CustomerID,sales);
}
class DoubleSales{
int CustomerID;
int ProductID;
int Units;
DoubleSales(int custID, int prodID, int Units){
CustomerID = custID;
ProductID = prodID;
Units = units;
}
}
导入文件的数据格式为
CustomerID, ProductID, UnitsSold
1,10002,3
1,10004,5
1,10008,2
1,10010,3
1,10010,3
使用上面的代码,当我打印 customerID 值 1 时,我只得到最后一个条目,即 10010,3。
我将如何打印出 CustomerID 1 的所有值和售出的单位?
for example:
1,10002,3
10004,5
10008,2
10010,3
10010,3
(will add the two 10010 values later.)
我不想使用数组列表。
最佳答案
尝试使用 Apache Common Collections 中的 MultiValueMap。
Click here更多引用
关于具有多个值的 Java hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42385301/