具有多个值的 Java hashmap

标签 java hashmap

我知道它被问了一百次,答案总是一样的,你不能在 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/

相关文章:

java - 是否可以使用 lambda 就地更改列表的值(无需创建新列表)?

Java HashMap<Integer, Integer> 与 int[]

java - 搜索但不需要按钮,JFrame

java - 在java中构建项目-项目矩阵

hashtable - 开放寻址与分离链接

python - 如何在 Python 中从包含 N 行的 csv 文件创建嵌套字典

java - 添加一个映射值来设置它是否与参数匹配

java - 单选按钮未取消选择

java - 无法使用 CAdES 方法签署 PDF,尽管使用 PAdES 签署成功

Java 模式正则表达式不匹配