본문 바로가기
Language/Java

컬렉션 프레임워크 4

by Zayne 2023. 2. 23.

■ Map<K, V> 인터페이스를 구현하는 컬렉션 클래스들

Map<K, V> 를 구현하는 컬렉션 클래스의 인스턴스들은 Key와 Value가 한 쌍을 이루는 형태

■ Map<K, V> 인터페이스를 구현하는 HashMap<K, V> 클래스의 사용 예시

 

import java.util.HashMap;

public class HashMapCollection {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();

        // Key-Value 기반 데이터 저장
        map.put(45, "Brown");
        map.put(37, "James");
        map.put(23, "Martin");

        // 데이터 탐색
        System.out.println("23번 : " + map.get(23));
        System.out.println("37번 : " + map.get(37));
        System.out.println("45번 : " + map.get(45));

        // 데이터 삭제
        map.remove(37);

        // 데이터 삭제 확인
        System.out.println("37번 : " + map.get(37));
    }
}

 

23번 : Martin
37번 : James
45번 : Brown
37번 : null

 

■ HashMap<K, V>의 순차적 접근 방법

HashMap<K, V> 클래스는 Iterable<T> 인터페이스를 구현하지 않으므로 다음 메소드를 통해

컬렉션 인스턴스를 생성하고, 여기에 Key를 담아야한다.

public Set<K> KeySet()

 

사용 예시

Set<Integer> ks = map.keySet();


// 전체 Key 출력
for(Integer n : ks)
System.out.print(n.toString());


// 전체 Value 출력
for(Integer n : ks)
System.out.print(map.get(n).toString());

 

■ TreeMap<K, V> 의 사용 예시 및 순차적 접근 방법

 

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

class AgeComparator implements Comparator<Integer> {
    public int compare(Integer n1, Integer n2) {
        return n2.intValue() - n1.intValue();
    }
}

public class ComparatorTreeMap {
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<>(new AgeComparator());

        // Key-Value 기반 데이터 저장
        map.put(45, "Brown");
        map.put(37, "James");
        map.put(23, "Martin");

        // Key만 담고 있는 컬렉션 인스턴스 생성
        Set<Integer> ks = map.keySet();

        // 전체 Key 출력 (for-each문 기반)
        for (Integer n : ks) {
            System.out.print(n.toString() + '\t');
        }
        System.out.println();

        // 전체 Value 출력 (for-each문 기반)
        for (Integer n : ks) {
            System.out.print(map.get(n).toString() + '\t');
        }
        System.out.println();

        // 전체 Value 출력 (반복자 기반)
        for (Iterator<Integer> itr = ks.iterator(); itr.hasNext();) {
            System.out.print(map.get(itr.next()) + '\t');
        }
        System.out.println();
    }
}

 

45      37      23
Brown   James   Martin
Brown   James   Martin

 

Comparator<T> 인터페이스를 기반으로 TreeSet<E> 의 정렬 기준을 결정할 수 있다.

위 예제에서는 내림차순으로 나이 정보가 출력되도록 정의하였다.

'Language > Java' 카테고리의 다른 글

네스티드 클래스와 이너 클래스  (0) 2023.02.27
컬렉션 프레임워크 5  (0) 2023.02.24
컬렉션 프레임워크 3  (0) 2023.02.22
컬렉션 프레임워크 2  (0) 2023.02.21
컬렉션 프레임워크 1  (0) 2023.02.20