[英]Java hashmap with Multiple values
我知道它被問了一百遍,答案總是一樣的,您不能在哈希圖中使用多個重復值。 但是讓我們解決問題。 我有一個導入文件,該導入文件包含有關CustomerID,ProductID和所售單位(其基本收據格式)的信息。 我想要做的是將導入內容放入地圖中,並能夠對其進行引用。
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。
點擊這里獲取更多參考
在您的情況下, 簡單的 Map
不會對您有所幫助,您寫入指定客戶價值的所有內容都會被覆蓋,如果要保留所有條目同時又易於引用,請嘗試:
Map<Integer,List<DoubleSales>> productData = new HashMap<Integer,List<DoubleSales>>();
List<DoubleSales> entries;
if(productData.get(CustomerID) == null) {
entries = new ArrayList<DoubleSales>();
entries.add(sales);
productData.put(CustomerID, entries);
} else {
List<DoubleSales> entries = productData.get(CustomerID);
entries.add(sales);
}
List<DoubleSales> products = productData.get(CustomerID);
if (products != null) {
for(DoubleSales product : products) {
// access your product here.
}
}
您已經復制了CustomerID
(所有ID均為1
),並將其用作Hashmap中的鍵。 這就是為什么當您插入具有相同ID的新記錄時,它會保持控制的原因。 看來您的產品ID是唯一的。 試試看或擁有唯一的客戶ID。
我認為在這種情況下,最好使用矩陣來實現該結構。 使用數組(或列表)可以很容易地做到這一點,其中的行可以包含一個由產品ID和所售單位構成的Bean,並由客戶ID進行索引
我的第一個想法是傑里·欽(Jerry Chin)的解決方案,但我想向您展示第二種方法,只是為了證明針對同一問題有多種解決方案。
您可以將值存儲在TreeSet<DoubleSales>
。 這不會限制輸入,您可以輸入例如1,10010,3
多次。
然后,在DoubleSales
上定義一個訂單( Comparator
),以按CustomerID將訂單分組。
打印列表時,可以檢查當前記錄的customerID與prevoius記錄是否不同。 如果不同,則它是新客戶的第一條記錄。 如果不是,則它屬於同一客戶。
和代碼:
SortedSet<DoubleSales> set = new TreeSet<DoubleSales>(new Comparator<DoubleSales>() {
@Override
public int compare(DoubleSales o1, DoubleSales o2) {
return Long.compare(o1.customerId, o2.customerId);
}
});
// ... import data
set.add(new DoubleSales( /*...*/ ));
// iterate through data
DoubleSales prevDS = null;
for (DoubleSales ds : set) {
if (prevDS == null || ds.customerId != prevDS.customerId) {
// first record of a customer
// print CustomerID, ProductID, UnitsSold
} else {
// second or next record of a customer
// print ProductID, UnitsSold only
}
prevDS = ds;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.