前言:
表格里需要对数据进行汇总展示,而用sql又不是很方便(以我的sql水平无法实现),
通过用list集合转换成map,再到map里进行数据的替换,将所需要的统计字段set进list的bean的属性中进行封装
代码实现:
public Map getJksForMap(String dwbm, String jksbh, Date begin, Date end) { // if (!org.apache.commons.Resources.code()) { // return new HashMap(); // } List list = accountQueryDao.getJks(dwbm, jksbh, begin, end); Map listMap = new HashMap(); Map totalMap = new HashMap(); Map statMap = new HashMap(); for (int i = 0; i < list.size(); i++) { QueryJks o = (QueryJks) list.get(i); if (listMap.get(o.getDwbm()) == null) { List lt = new ArrayList(); lt.add(o); listMap.put(o.getDwbm(), lt); totalMap.put(o.getDwbm(), o.getSjje()); } else { List lt = (List) listMap.get(o.getDwbm()); lt.add(o); BigDecimal sum = (BigDecimal) totalMap.get(o.getDwbm()); totalMap.put(o.getDwbm(), sum.add(o.getSjje())); } } if (StringUtils.isNotBlank(dwbm)) { statMap = getStatJksForYear(dwbm, Integer.valueOf(DateUtil .formatDate(begin, "yyyy"))); } Iterator it = listMap.keySet().iterator(); while (it.hasNext()) { String dw = (String) it.next(); List lt = (List) listMap.get(dw); QueryJks o = new QueryJks(); o.setXmbm("以上合计"); o.setXmmc("记录数:" + lt.size()); o.setSjje((BigDecimal) totalMap.get(dw)); lt.add(o); if (statMap.get(dw) != null) { lt.addAll((List) statMap.get(dw)); } } return listMap; } public Map getStatJksForYear(String dwbm, Integer year) { Map statMap = accountQueryDao.getStatJksForYear(dwbm, year); BigDecimal stat = new BigDecimal("0"); QueryJks o = new QueryJks(); Iterator it = statMap.keySet().iterator(); while (it.hasNext()) { String dw = (String) it.next(); List lt = (List) statMap.get(dw); stat = new BigDecimal("0"); Iterator listLt = lt.iterator(); while (listLt.hasNext()) { o = (QueryJks) listLt.next(); stat = stat.add(o.getSjje()); o.setKprq("本月累计"); o.setJkr(FormatUtil.formatCurrency(stat.doubleValue())); } QueryJks bnlj = new QueryJks(); bnlj.setDwbm(dw); bnlj.setXmbm("本年累计"); bnlj.setSjje(stat); lt.add(bnlj); } return statMap; }
说明:
这里的map实则分为三个map,一个是原始数据,一个是累加的统计金额,一个是通过月份查询出来的统计金额
其中的文字说明等字段设为bean中的某个属性
注意:
Iterator it = listMap.keySet().iterator(); while (it.hasNext()) { String dw = (String) it.next(); List lt = (List) listMap.get(dw); QueryJks o = new QueryJks(); o.setXmbm("以上合计"); o.setXmmc("记录数:" + lt.size()); o.setSjje((BigDecimal) totalMap.get(dw)); lt.add(o); if (statMap.get(dw) != null) { lt.addAll((List) statMap.get(dw)); } }
这里运用迭代器往map里添加list集合
页面效果:
tips:
虽然项目版本比较老(都还没有泛型),但是这种巧妙的封装思想依旧是值得学习的