Java - Collection Util

JeongHoHyun·2025년 1월 7일

Java

목록 보기
16/23

Collection 정렬 관련 메서드

  • max : 정렬 기준으로 최대 값을 찾아서 반환한다.
  • min : 정렬 기준으로 최소 값을 찾아서 반환한다.
  • shuffle : 컬렉션을 랜덤하게 섞는다.
  • sort : 정렬 기준으로 컬렉션을 정렬한다.
  • reverse : 정렬 기준의 반대로 컬렉션을 정렬한다.

편리한 불변 컬렉션 생성

  • List.of() : 불변 List 생성
  • Set.of() : 불변 Set 생성
  • Map.of() : 불변 Map 생성
  • emptyList() : 비어있는 불변 객체 생성
public static void main(String[] args) {
        // 편리한 불변 컬렉션 생성
        List<Integer> list = List.of(1, 2, 3);
        Set<Integer> set = Set.of(1, 2, 3);
        Map<Integer, String> map = Map.of(1, "one", 2, "two", 3, "three");

        System.out.println("list = " + list);
        System.out.println("set = " + set);
        System.out.println("map = " + map);
        
        // java.lang.UnsupportedOperationException 예외 발생
        // list.add(4);
        
        // 반 불변 리스트 생성
        List<Integer> list2 = Collections.emptyList(); // 자바 5
        List<Integer> list3 = List.of(); // 자바 9
    }
  • 불변이기 때문에 값을 바꿀 수 없다.

불변 -> 가변 -> 불변 변경

  • unmodifiableList() : 가변을 불변으로 변경
public class ImmutableMain {
    public static void main(String[] args) {
        // 불변 리스트 생성
        List<Integer> list = List.of(1, 2, 3);

        // 가변 리스트
        ArrayList<Integer> mutableList = new ArrayList<>(list);
        mutableList.add(4);
        System.out.println("mutableList = " + mutableList);

        // 불변 리스트
        List<Integer> unmodifiableList = Collections.unmodifiableList(mutableList);
        System.out.println("unmodifiableList class = " + unmodifiableList.getClass());
    }
}

멀티스레드 동기화

  • Collections.synchronizedList를 사용하면 일반 리스트를 멀티스레드 상황에서 동기화 문제가 발생하지 않는 안전한 리스트로 만들 수 있다.
  • 동기화 작업으로 인해 일반 리스트보다 성능은 더 느리다.
package collection.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SyncMain {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        System.out.println("list class = " + list.getClass());
        List<Integer> synchronizedList = Collections.synchronizedList(list);
        System.out.println("synchronizedList.getClass() = " + synchronizedList.getClass());
    }
}
profile
Java Back-End 2022.11.01 💻~ing

0개의 댓글