2016-01-18 86 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'。” –