zoukankan      html  css  js  c++  java
  • HashMap合并相同key的value

        Map<String, String> map1 = new HashMap<>();
            map1.put("x", "y");
            map1.put("a", "b");
            map1.put("c", "d");
            map1.put("e", "d");
            map1.put("f", "b");
            map1.put("m", "n");
    
            Map<String, ArrayList<String>> map2 = new HashMap<>();
            String entryValue = null;
            String entryKay = null;
            ArrayList<String> tmpValue = new ArrayList<>();
            ArrayList<String> tmpMap2Value = new ArrayList<>();
    
            for (Entry<String, String> entry : map1.entrySet()) {
                tmpValue.clear();
                tmpMap2Value.clear();
                entryKay = entry.getKey();
                entryValue = entry.getValue();
    
                if (map2.keySet().contains(entryValue)) {
                    tmpMap2Value = map2.get(entryValue);
                    tmpMap2Value.add(entryKay);
                    map2.put(entryValue, (ArrayList<String>) tmpMap2Value.clone());
                } else {
                    tmpValue.add(entryKay);
                    map2.put(entryValue, (ArrayList<String>) tmpValue.clone());
                }
            }
            System.out.println(map2);

    Java不能 通过简单的赋值来解决对象复制的问题,需要利用clone实现。

  • 相关阅读:
    59、web框架以及Django框架
    58、bootstrap
    56、jQuery事件
    55、原生js事件与jQuery
    36-并发编程
    4.20---远程执行命令的CS架构软件
    35-socket 基于套接字的TCP与UDP
    34-网络编程
    33-异常处理
    4.15---元类练习
  • 原文地址:https://www.cnblogs.com/felixzh/p/6019444.html
Copyright © 2011-2022 走看看