2016-01-18 87 views
-2

我有一個如下的憑證ArrayListList。從ArrayList中檢索並使用hashmap存儲到新的Arraylist中

voucherlist的ArrayList

[0] voucher 
     carrierCode "UPS" 
     originShippingLocationCode "L998" 
     systemVoucherID "000000000632" 
    [1] voucher 
     carrierCode "UPS" 
     originShippingLocationCode "L998" 
     systemVoucherID "000000000633" 
    [2] voucher 
     carrierCode "UPS" 
     originShippingLocationCode "L998" 
     systemVoucherID "000000000634" 
    [3] voucher (id=2744) 
     carrierCode "FEDEX" 
     originShippingLocationCode "L998" 
     systemVoucherID "000000000638" 
    [4] voucher  
     carrierCode "FEDEX" 
     originShippingLocationCode "L998" 
     systemVoucherID "000000000639" 
    [5] voucher  
     carrierCode "UPS" 
     originShippingLocationCode "L1003"  
     systemVoucherID "000000000636" 
    [6] voucher  
     carrierCode "UPS" 
     originShippingLocationCode "L1003"  
     systemVoucherID "000000000637" 
    [7] voucher 
     carrierCode "UPS" 
     originShippingLocationCode "L1001"  
     systemVoucherID "000000000635" 

我不得不組(創建新的ArrayList),其具有相同的originShippingLocationCode憑單。例如:

例如:具有originShippingLocationCode =「L998」的所有優惠券給一個新的ArrayList。

我不知道originShippingLocationCode的值是否會發生變化。我從API調用中獲取這些數據作爲響應。

任何人都可以幫助解決這個問題嗎?

我想使用Hashmap創建一個新的ArrayList,當檢測到originShippingLocationCode時,將originShippingLocationCode保持爲'Key'。

預先感謝。

回答

2

你絕對可以使用這個HashMap,這裏有一個例子:

ArrayList<Voucher> vouchers = new ArrayList<Voucher>(); 
... 
HashMap<String, ArrayList<Voucher>> groups = new HashMap<String, ArrayList<Voucher>>(); 
for (Voucher v : vouchers) { 
    if (groups.containsKey(v.getOriginShippingLocationCode())) { 
     groups.get(v.getOriginShippingLocationCode()).add(v); 
    } else { 
     groups.put(v.getOriginShippingLocationCode(), new ArrayList<Voucher>(Arrays.asList(new Voucher[] { v }))); 
    } 
} 
+0

我的要求現在已更改。 –

+0

我必須根據originShippingLocationCode和carrierCode將憑證分組。你能幫我解決這個問題嗎? @Titus –

+0

@ vijay.k你可以將這些值連接成一個'String'並使用它具有映射關鍵字。 – Titus

0

因此,從我可以收集的信息中,您要搜索當前的數組並取出所有具有特定送貨地點的憑證?

你可以做,使用類似於以下

for (Voucher v : vouchers) { 
    if (v.getOriginShippingLocationCode().equals("L998")) { 
     //.. add to new array list 
    } 
} 

這將循環通過的東西你所有的憑證和裝運位置代碼比較指定的一個。如果它匹配,你可以做你喜歡的事情。

編輯

如果你不知道託運地點(一定是我錯過了一部分從OP),你可以使用地圖,也許有你的託運地點爲重點,這樣你就可以只需獲得與特定地點相關的所有優惠券即可。

Map<String, List<Voucher>> vouchers = new HashMap<>(); 

建立新的列表基於密鑰,然後vouchers.put(key, newList);

+0

的問題指出:「我不知道知道將會改變originShippingLocationCode的價值是什麼。「所以這不會很有用。 –

+2

更好的方式是OP已經建議的。 「我想在檢測到originShippingLocationCode時使用Hashmap創建一個新的ArrayList,並將originShippingLocationCode保持爲'Key'。」 –