PHpullh
학습 라이브러리/Java/Collections Framework 핵심

JAVA · 컬렉션

Collections Framework 핵심

ArrayList, LinkedList, HashMap, LinkedHashMap, TreeMap, HashSet의 선택 기준과 사용법.

컬렉션입문ArrayListHashMapTreeMapLinkedHashMapcomputeIfAbsent

핵심 설명

ArrayList, LinkedList, HashMap, LinkedHashMap, TreeMap, HashSet의 선택 기준과 사용법.

Java code

import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        // List — 순서 있는 중복 허용
        List<String> arrayList = new ArrayList<>();    // 조회 O(1)
        List<String> linkedList = new LinkedList<>();  // 삽입/삭제 O(1)
        List<String> immutable = List.of("a", "b", "c"); // 불변 (Java 9+)

        arrayList.addAll(List.of("banana", "apple", "cherry"));
        Collections.sort(arrayList);
        System.out.println(arrayList); // [apple, banana, cherry]

        // Map — 키-값, 키 중복 불가
        Map<String, Integer> hashMap    = new HashMap<>();   // 순서 없음
        Map<String, Integer> linkedMap  = new LinkedHashMap<>(); // 삽입 순서
        Map<String, Integer> treeMap    = new TreeMap<>();   // 키 정렬

        hashMap.put("banana", 2);
        hashMap.put("apple", 1);
        hashMap.put("cherry", 3);

        // getOrDefault, putIfAbsent, computeIfAbsent
        hashMap.getOrDefault("durian", 0);
        hashMap.putIfAbsent("apple", 99);     // apple 이미 있어 무시
        hashMap.computeIfAbsent("elderberry", k -> k.length());
        hashMap.merge("apple", 5, Integer::sum); // apple = 1+5 = 6

        // 순회
        hashMap.forEach((k, v) ->
            System.out.println(k + ": " + v));

        // Set — 중복 없음
        Set<String> hashSet  = new HashSet<>(arrayList);  // 순서 없음
        Set<String> treeSet  = new TreeSet<>(arrayList);  // 정렬
        Set<String> immSet   = Set.of("x", "y", "z");     // 불변

        // Collections 유틸리티
        System.out.println(Collections.max(arrayList));
        System.out.println(Collections.frequency(arrayList, "apple"));
        Collections.shuffle(arrayList);
        Collections.reverse(arrayList);
        Collections.unmodifiableList(arrayList);  // 불변 뷰
    }
}

학습 팁

List.of(), Set.of(), Map.of()(Java 9+)는 null을 허용하지 않고 크기가 고정된 불변 컬렉션을 반환합니다.

주의할 점

ArrayListfor(int i=0; i로 순회하며 중간에 삭제하면 ConcurrentModificationException이 납니다. Iterator.remove()removeIf()를 사용하세요.

자주 묻는 질문

Collections Framework 핵심란 무엇인가요?

ArrayList, LinkedList, HashMap, LinkedHashMap, TreeMap, HashSet의 선택 기준과 사용법.

Collections Framework 핵심 학습 시 주의할 점은 무엇인가요?

ArrayList 를 for(int i=0; i 로 순회하며 중간에 삭제하면 ConcurrentModificationException 이 납니다. Iterator.remove() 나 removeIf() 를 사용하세요.