[๋ณต์Šต] Collection

์ฃฝ๋ถ€์ธยท2023๋…„ 2์›” 2์ผ
0

๐Ÿ“ŒMap

๐Ÿ“˜์ค‘์ฒฉ Map + iterator + ์ง€๋„ค๋ฆญ

๐Ÿ‘€ ์ค‘์ฒฉ Map ์ง€๋„ค๋ฆญ์— ๋Œ€ํ•ด ํ™•์‹คํ•˜์ง„ ์•Š๋‹ค. ๋‚˜์ค‘์— ์ˆ˜์ •ํ•˜๋”๋ผ๋„ ๊ธฐ์กด์˜ˆ์ œ๋ฅผ ์ด๋ ‡๊ฒŒ ๊ณ ์น˜๋ฉด ๋ฌธ์ œ๊ฐ€ ์—†๊ธธ๋ž˜ ์šฐ์„ ์€ ๊ธฐ๋กํ•ด๋‘”๋‹ค.


public class Map_map_Generic {
    static HashMap<String, HashMap<String, String>> phoneBook = new HashMap<>();

    public static void main(String[] args) {
        addPhoneNo("์นœ๊ตฌ", "์ฃฝ๋ถ€์ธ1", "10");
        addPhoneNo("์นœ๊ตฌ", "์ฃฝ๋ถ€์ธ2", "11");
        addPhoneNo("์นœ๊ตฌ", "์ฃฝ๋ถ€์ธ3", "12");
        addPhoneNo("ํšŒ์‚ฌ", "์ฃฝ๋ถ€์ธ7", "20");
        addPhoneNo("ํšŒ์‚ฌ", "์ฃฝ๋ถ€์ธ8", "21");
        addPhoneNo("ํšŒ์‚ฌ", "์ฃฝ๋ถ€์ธ9", "22");
        addPhoneNo("๋™๋„ค", "์ฃฝ๋ถ€์ธ4", "30");
        addPhoneNo("์นœ๊ตฌ", "์ฃฝ๋ถ€์ธ5", "13");
        addPhoneNo("์ƒ๊ฐ€", "40");

        printList();
    }

    static void addPhoneNo(String groupName, String name, String tel) {
        addGroup(groupName);
        HashMap<String, String> group = phoneBook.get(groupName);
        group.put(tel, name);
    }

    static void addGroup(String groupName) {
        if (!phoneBook.containsKey(groupName))
            phoneBook.put(groupName, new HashMap());
    }

    static void addPhoneNo(String name, String tel) {
        addPhoneNo("๊ธฐํƒ€", name, tel);
    }

    static void printList() {
    
        Set<Map.Entry<String, HashMap<String, String>>> set = phoneBook.entrySet();     //๋ฐ”๊นฅ์ชฝ Map
        Iterator<Map.Entry<String, HashMap<String, String>>> it = set.iterator();

        while (it.hasNext()) {
            Map.Entry<String, HashMap<String, String>> e = it.next();    //๋ฐ”๊นฅ์ชฝ Map it

            Set<Map.Entry<String, String>> subSet = e.getValue().entrySet();   //์•ˆ์ชฝ Map
            Iterator<Map.Entry<String, String>> subIt = subSet.iterator();

            System.out.println(" * " + e.getKey() + "[" + subSet.size() + "]");
            while (subIt.hasNext()) {
                Map.Entry<String, String> subE = subIt.next();  //์•ˆ์ชฝ Map it

                String telNo = (String) subE.getKey();
                String name = (String) subE.getValue();
                System.out.println(name + " " + telNo);
            }
            System.out.println();

        }
    }

}

์ถœ์ฒ˜ : ์ž๋ฐ”์˜ ์ •์„

profile
์—ฐ์Šต์žฅ ์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€