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));
          }
    }
    }
  • 相关阅读:
    【02】Nginx:基本配置和日志处理
    【01】Nginx:编译安装/动态添加模块
    【09】Jenkins:Pipeline 补充
    【08】Jenkins:关于发布
    【07】Jenkins:流水线(Pipeline)
    【06】Jenkins:Gitlab 自动触发构建以及钉钉通知
    【05】Jenkins:用户权限管理
    【04】Jenkins:基本功能补充说明
    【03】Jenkins:SonarQube
    【02】Jenkins:第一个项目
  • 原文地址:https://www.cnblogs.com/xieshuang/p/5739853.html
Copyright © 2011-2022 走看看