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));
          }
    }
    }
  • 相关阅读:
    linux修改主机名
    selinux详解及配置文件
    linux磁盘分区
    识别光纤,模块
    free命令详解
    Linux系统修改网卡名(eth0-3)
    CentOS7的systemctl使用
    ELK集群
    ELK故障:elk在运行一段时间后,没有数据。
    superviosrd进程管理
  • 原文地址:https://www.cnblogs.com/xieshuang/p/5739853.html
Copyright © 2011-2022 走看看