공공부하자개발 · 영어 학습 노트
자바
중급객체지향과 코어 라이브러리0/9 완료
  • 01상속, 다형성, 오버라이딩
  • 02추상 클래스 vs 인터페이스
  • 03예외 처리
  • 04java.lang 심화
  • 05컬렉션 프레임워크 딥다이브
  • 06메서드 활용 패턴 (중급)
  • 07Object 메서드와 비교
  • 08java.time 실무 날짜 계산
  • 09HTTP 와 JSON 기초
사이트 소개개인정보처리방침연락처
© 2026 공부하자
홈 › 중급 › 05 / 9

컬렉션 프레임워크 딥다이브

섹션 7진행 0 / 9
1왜 배우는가2핵심 원리3코드 예제4응용 변형 예제5자주 하는 실수 (Tip)6연습 문제7정리‹ 이전다음 ›

6. 연습 문제

문제 1: 단어 빈도 상위 N개

문자열 "the quick the lazy the dog quick"에서 단어별 빈도를 세고, 빈도 내림차순(같으면 단어 오름차순)으로 상위 2개를 출력하라. Map.merge와 Comparator 조합을 사용할 것.

정답 보기
java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        String text = "the quick the lazy the dog quick";
        Map<String, Integer> freq = new HashMap<>();
        for (String w : text.split(" ")) freq.merge(w, 1, Integer::sum);

        List<Map.Entry<String, Integer>> entries = new ArrayList<>(freq.entrySet());
        entries.sort(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder())
                              .thenComparing(Map.Entry.comparingByKey()));

        for (int i = 0; i < 2; i++) {
            System.out.println(entries.get(i).getKey() + "=" + entries.get(i).getValue());
        }
        // 출력:
        // the=3
        // quick=2
    }
}

문제 2: 최근 본 상품 (LRU) 직접 구현

LinkedHashMap을 상속하지 않고 컴포지션으로, 최대 3개의 최근 본 상품 ID를 유지하는 RecentlyViewed 클래스를 만들어라. view(String id) 호출 시 이미 있으면 최신으로 갱신, 초과 시 가장 오래된 것을 제거하며, ids()는 오래된 것부터 최신 순 리스트를 반환한다.

view("A"), view("B"), view("C"), view("A"), view("D") 후 ids()가 [C, A, D]여야 한다.

정답 보기
java
import java.util.*;

class RecentlyViewed {
    private final int capacity;
    private final LinkedHashMap<String, Boolean> map = new LinkedHashMap<>(16, 0.75f, true);

    RecentlyViewed(int capacity) { this.capacity = capacity; }

    void view(String id) {
        map.put(id, Boolean.TRUE);                          // accessOrder → 맨 뒤로
        if (map.size() > capacity) {
            String eldest = map.keySet().iterator().next();  // 맨 앞 = 가장 오래된 것
            map.remove(eldest);
        }
    }

    List<String> ids() { return new ArrayList<>(map.keySet()); }
}

public class Main {
    public static void main(String[] args) {
        RecentlyViewed rv = new RecentlyViewed(3);
        for (String id : List.of("A", "B", "C", "A", "D")) rv.view(id);
        System.out.println(rv.ids());   // 출력: [C, A, D]
    }
}

문제 3: 주문 상태 전이 검증 (Map + Set)

허용된 상태 전이 CREATED→PAID, PAID→SHIPPED, PAID→CANCELLED, SHIPPED→DELIVERED를 Map<String, Set<String>>으로 정의하고, canTransit(from, to)를 작성하라. 없는 상태에서 조회해도 NPE가 나면 안 된다. CREATED→PAID(true), PAID→DELIVERED(false), UNKNOWN→PAID(false)를 출력하라.

정답 보기
java
import java.util.Map;
import java.util.Set;

public class Main {
    static final Map<String, Set<String>> TRANSITIONS = Map.of(
        "CREATED", Set.of("PAID"),
        "PAID",    Set.of("SHIPPED", "CANCELLED"),
        "SHIPPED", Set.of("DELIVERED")
    );

    static boolean canTransit(String from, String to) {
        return TRANSITIONS.getOrDefault(from, Set.of()).contains(to);   // 없는 키 → 빈 Set
    }

    public static void main(String[] args) {
        System.out.println(canTransit("CREATED", "PAID"));     // 출력: true
        System.out.println(canTransit("PAID", "DELIVERED"));   // 출력: false
        System.out.println(canTransit("UNKNOWN", "PAID"));     // 출력: false
    }
}
연습 문제
  • 문제 1: 단어 빈도 상위 N개
  • 문제 2: 최근 본 상품 (LRU) 직접 구현
  • 문제 3: 주문 상태 전이 검증 (Map + Set)
이전 섹션5 자주 하는 실수 (Tip)6 / 7다음 섹션7 정리