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实现。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM