zoukankan      html  css  js  c++  java
  • map合并,相同键对应的值相加

    最近在做统计钱的计算时遇到的一个需求,需要将一个大类别下的每一种钱进行特定的运算然后获得六年的钱,最后将这些钱按照年份进行汇总,获得总得大类型的六年的钱,在这个过程中采用了这种方法,每次算得钱放在map中,然后将map进行合并,写篇随笔mark下。

    public class CombineMap {
    public static Map<Integer,Integer> addTo(Map<Integer,Integer> target, HashMap<Integer,Integer>plus) {
        Object[] os = plus.keySet().toArray();
        Integer key;
        for (int i=0; i<os.length; i++) {
            key = (Integer)os[i];
            if (target.containsKey(key)) 
                target.put(key, target.get(key) + plus.get(key));
            else
                target.put(key, plus.get(key));
        }
        return target;
    }
    
    public static void main(String[] args) {
                // 获得arm,body,head,leg,wst
                // ......
        Map<Integer,BigDecimal> all = new TreeMap<Integer,BigDecimal>();
          all.put(2016, new BigDecimal(10));
          all.put(2017, new BigDecimal(10));
          all.put(2018, new BigDecimal(10));
          all.put(2019, new BigDecimal(10));
          all.put(2020, new BigDecimal(10));
    
          Map<Integer,BigDecimal> plus = new HashMap<Integer,BigDecimal>();
          plus.put(2016, new BigDecimal(1));
          plus.put(2017, new BigDecimal(2));
          plus.put(2018, new BigDecimal(3));
          plus.put(2019, new BigDecimal(4));
          plus.put(2020, new BigDecimal(5));
    
          all = addTo(all, plus);
          all = addTo(all, plus);
          List<BigDecimal> tepList;
          tepList = new ArrayList<BigDecimal>();
          for (Object s : all.keySet()) {
              System.out.print("year : " + s);
              System.out.println("  values : " + all.get(s).doubleValue());
              tepList.add(all.get(s));
          }
    }
    }
  • 相关阅读:
    如何禁止在DBGRID末位自动添加一行记录
    DELPHI加密字串(异或运算加密)
    SQL SERVER 正则替换
    sql里的正则表达式
    UFIDA
    delphi raise 语句: 抛出异常
    delphi怎么一次性动态删除(释放)数个动态创建的组件?
    Delphi动态创建组件,并释放内存
    DELPHI 动态 创建和释放 多个 EDIT 控件
    禁止在DBGrid中按delete删除记录
  • 原文地址:https://www.cnblogs.com/xieshuang/p/5739853.html
Copyright © 2011-2022 走看看