首页 > 技术文章 > list集合根据字段分组统计转换成map

wutongshu-master 原文

前言

表格需要对数据进行统计

代码实现

	public Map getUnitStoreSum(String unitId, String billCode) {
		List store=listUnitStore(unitId, billCode);
		Map groupMap=new HashMap();
		for(int i=0;i<store.size();i++){        
			NoteStorageInfo nsi=(NoteStorageInfo) store.get(i); 
			List tempList=(List) groupMap.get(nsi.getPjmc());
            if (tempList == null) {
                tempList = new ArrayList();
                tempList.add(nsi);
                groupMap.put(nsi.getPjmc(), tempList);
            }
            else {
                tempList.add(nsi);  //这里的tempList表示的是groupMap.get(nsi.getPjmc())的引用,所以往里面追加值也就会改变map里的值
            }
		}
		Map sum=new HashMap();
		Iterator it = groupMap.keySet().iterator();
		while (it.hasNext()) {
			String pj = (String) it.next();
			List ns=(List)groupMap.get(pj);
			int sl=0;
			for(int i=0;i<ns.size();i++){
				NoteStorageInfo n=(NoteStorageInfo) ns.get(i);
				sl+=n.getSl();
			}
			sum.put(pj, new Integer(sl));
		}
		
		return sum;
	}

over

推荐阅读