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