Java

112. HashMap - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2025. 1. 2. 18:03

1. HashMap과 Hashtalbe - 순서X, 중복(키X, 값O)

  • Map인터페이스를 구현, 데이터를 키와 값의 쌍으로 저장
  • HashMap(동기화X)은 Hashtable(동기화O)의 신버젼

2. HashMap

  • Map인터페이스를 구현한 대표적인 컬렉션 클래스
  • 순서를 유지하려면 LinkedHashMap클래스를 사용하면 된다.

3. TreeMap

  • 범위 검색과 정렬에 유리한 컬렉션 클래스
  • HashMap보다 데이터 추가, 삭제에 시간이 더 걸림

4. HashMap의 키(key)와 값(value)

  • 해싱(hashing)기법으로 데이터를 저장, 데이터가 많아도 검색이 빠르다.
  • Map인터페이스를 구현, 데이터를 키와 값의 쌍으로 저장

5. 해싱(hasing)

  • 해시함수(hash function)로 해시테이블(hash table)에 데이터를 저장 검색
  • 해시테이블은 배열과 링크드 리스트가 조합된 형태
  • 서로 다른 키일지라도 같은 값의 해시코드를 반환할 수도 있다.(같은 배열에 있는 링크드 리스트)
        HashMap map = new HashMap();
        map.put("myId", "1234");
        map.put("asdf", "1111");
        System.out.println(map);    // {myId=1234, asdf=1111}
        map.put("asdf", "1234");
        System.out.println(map);    // {myId=1234, asdf=1234}

        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("id와 password를 입력해주세요.");
            System.out.print("id : ");
            String id = sc.nextLine().trim();

            System.out.print("password : ");
            String password = sc.nextLine().trim();
            System.out.println();

            if (!map.containsKey(id)) {
                System.out.println("입력하신 id는 존재하지 않습니다. 다시 입력해주세요.");
                continue;
            }

            // map.get(key) -> value반환
            if (!(map.get(id).equals(password))) {
                System.out.println("비밀번호가 일치하지않습니다. 다시 입력해주세요.");
                continue;
            } else {
                System.out.println("id와 비밀번호가 일치합니다.");
                break;
            }
        }

 

6. 예제 - 2

        HashMap map = new HashMap();
        map.put("김자바", new Integer(90));
        map.put("김자바", new Integer(100));
        map.put("이자바", new Integer(100));
        map.put("강자바", new Integer(80));
        map.put("안자바", new Integer(90));

        Set set = map.entrySet();
        Iterator it = set.iterator();

        while (it.hasNext()) {
        // Map인터페이스 안에 있는 Entry인터페이스
            Map.Entry e = (Map.Entry)it.next();
            System.out.println("이름 : " + e.getKey() + ", 점수 : " + e.getValue());
        }

        set = map.keySet();
        System.out.println("참가자 명단 : " + set);

        Collection values = map.values();
        it = values.iterator();

        int total = 0;

        while (it.hasNext()) {
            int i = (int)it.next();
            total += i;
        }

        System.out.println("총점 : " + total);
        System.out.println("평균 : " + (float)total/set.size());
        System.out.println("최고점수 : " + Collections.max(values));
        System.out.println("최저점수 : " + Collections.min(values));

 

7. 예제 - 3

    public static void main(String[] args) {
        String[] data = {"A","K","A","K","D","K","A","K","K","K","Z","D"};

        HashMap map = new HashMap();

        for (int i = 0; i < data.length; i++) {
            if (map.containsKey(data[i])) {
                int value = (int) map.get(data[i]);
                map.put(data[i], value + 1);
            } else {
                map.put(data[i], 1);
            }
        }

        Iterator it = map.entrySet().iterator();;

        while (it.hasNext()) {
            Map.Entry e = (Map.Entry)it.next();
            int value = (int)e.getValue();
            System.out.println(e.getKey() + " : "
                    + printBar('#', value) + " " + value);
        }
    }
    static String printBar(char ch, int value) {
        String str = "";
        for (int i = 0; i < value; i++) {
            str += ch;
        }
        return str;
    }