为避免与数据库的多次连接,减少数据库的压力,先将所有的订货数据先从数据库中抽取出来,而后再将数据按门店进行分类汇总以备待用,Map与List混合操作,理解数据结构。提神醒脑哦。
以下是原始数据结构:
[{store_id=020, GoodsCode=04304654, Qty=8.000},
{store_id=956, GoodsCode=04304685, Qty=7.000},
{store_id=956, GoodsCode=04304715, Qty=6.000},
{store_id=956, GoodsCode=04304722, Qty=2.000}]
以下是想要的数据结构:
[
{store_id=020, orderList=[{GoodsCode=04304654, Qty=8.000}]},
{store_id=956, orderList=[{GoodsCode=04304685, Qty=7.000},{GoodsCode=04304715, Qty=6.000},{GoodsCode=04304722, Qty=2.000}]}
]
以下是实现代码:
1.用一层循环从数据中找出门店的store_id;
2.通过判断循环的store_id是否在新创建的数组中存在来保证其唯一性;
3.在用唯一的store_id来获取属于该门店的订货信息
1 public List<Map<String, Object>> allOrderedStore(List<Map<String, Object>> allStoreOrderDetails) { 2 List<String> storeList = new ArrayList<String>(); 3 List<Map<String, Object>> allOrderedStoreList =new ArrayList<Map<String, Object>>(); 4 5 for (int i = 0; i < allStoreOrderDetails.size(); i++) 6 { 7 String storeId=allStoreOrderDetails.get(i).get("store_id").toString(); 8 9 if (!storeList.contains(storeId)) 10 { 11 storeList.add(storeId); 12 Map<String, Object> Map = new HashMap<String, Object>(); 13 Map.put("storeid", storeId); 14 List<Map<String, Object>> orderlist =new ArrayList<Map<String, Object>>(); 15 for (int j = 0; j < allStoreOrderDetails.size(); j++) { 16 if(storeId.equals(allStoreOrderDetails.get(j).get("store_id"))){ 17 Map<String, Object> orderMap = new HashMap<String, Object>(); 18 orderMap.put("GoodsCode", allStoreOrderDetails.get(j).get("GoodsCode")); 19 orderMap.put("Qty", allStoreOrderDetails.get(j).get("Qty")); 20 orderlist.add(orderMap); 21 } 22 } 23 Map.put("orderList", orderlist); 24 allOrderedStoreList.add(Map); 25 } 26 } 27 return allOrderedStoreList; 28 }