Collections 클래스는 Java에서 컬렉션 객체(List, Set, Map 등)를 조작하기 위한 유틸리티 메서드를 제공한다.
데이터를 정렬, 검색, 변환하거나 통계 계산 등의 작업을 간단히 처리할 수 있음.
Collections의 주요 특징
1. 유틸리티 클래스
- 컬렉션 데이터 구조를 조작하기 위한 다양한 정적 메서드를 제공한다.
- 컬렉션의 정렬, 역순, 검색, 빈도 계산 등을 간단히 수행
2. 범용적 사용
- List, Set, Map 등 모든 컬렉션 객체와 함께 사용 가능
3. 안전성
- 동기화된 컬렉션 생성 메서드( synchronizedList, synchronizedSet 등)를 제공해 스레드 안전성을 보장.
4. 메서드 제공
메서드 | 설명 |
sort(List) | 리스트를 오름차순으로 정렬 |
reverse(List) | 리스트의 순서를 역순으로 변경 |
shuffle(List) | 리스트의 요소를 무작위로 섞음 |
max(Collection) | 컬렉션에서 최대값 반환 |
min(Collection) | 컬렉션에서 최소값 반환 |
frequency(Collection, Object) | 특정 요소의 등장 횟수 반환 |
synchronizedList(List) | 동기화된 리스트 생성 |
swap(List, int, int) | 리스트의 두 요소를 교환 |
예제 코드
1) 정렬하기 (sort)
List<Integer> list = Arrays.asList(5, 3, 8, 1, 2);
Collections.sort(list);
System.out.println("정렬된 리스트: " + list); // 출력: [1, 2, 3, 5, 8]
2) 역순으로 변경 (reverse)
Collections.reverse(list);
System.out.println("역순 리스트: " + list); // 출력: [8, 5, 3, 2, 1]
3) 무작위로 섞기 (shuffle)
Collections.shuffle(list);
System.out.println("섞인 리스트: " + list); // 출력: [3, 8, 1, 2, 5] (랜덤)
4) 최대값/최소값 찾기 (max, min)
int max = Collections.max(list);
int min = Collections.min(list);
System.out.println("최대값: " + max + ", 최소값: " + min); // 출력: 최대값: 8, 최소값: 1
5) 특정 값 빈도 확인 (frequency)
int freq = Collections.frequency(list, 3);
System.out.println("3의 빈도수: " + freq); // 출력: 1
6) 두 요소 교환 (swap)
Collections.swap(list, 0, 2);
System.out.println("교환된 리스트: " + list); // 출력: [8, 5, 3, 1, 2] (예시)
7) 동기화된 리스트 생성 (synchronizedList)
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>(list));
System.out.println("동기화된 리스트 생성 완료!");
실습
문제
학생 점수를 저장한 리스트를 Collections 클래스를 사용해 정렬, 분석, 변환 작업 수행.
풀이
import java.util.*;
public class Main {
public static void main(String[] args) {
// 1️⃣ 학생 점수 리스트 생성
List<Integer> scores = new ArrayList<>(Arrays.asList(85, 70, 92, 88, 76));
// 2️⃣ 정렬 (오름차순)
Collections.sort(scores);
System.out.println("정렬된 점수: " + scores); // 출력: [70, 76, 85, 88, 92]
// 3️⃣ 역순 변경
Collections.reverse(scores);
System.out.println("역순 점수: " + scores); // 출력: [92, 88, 85, 76, 70]
// 4️⃣ 최대값, 최소값 출력
int maxScore = Collections.max(scores);
int minScore = Collections.min(scores);
System.out.println("최고 점수: " + maxScore); // 출력: 92
System.out.println("최저 점수: " + minScore); // 출력: 70
// 5️⃣ 무작위 섞기
Collections.shuffle(scores);
System.out.println("섞인 점수: " + scores); // 출력: [88, 70, 92, 85, 76] (랜덤)
// 6️⃣ 특정 점수의 빈도 확인
int freq = Collections.frequency(scores, 85);
System.out.println("85점의 빈도수: " + freq); // 출력: 1
}
}
정리
1. Collections 클래스의 주요 기능
- 데이터 정렬, 검색, 변환, 빈도 계산 등 컬렉션 조작 기능 제공.
- 컬렉션 객체의 생산성을 높이고 코드 작성이 간단해짐.
2. 활용성
- List, Set, Map 등 Java의 다양한 컬렉션 클래스와 함께 사용 가능.
- 복잡한 데이터 작업을 간단하게 수행.
'Coding Test' 카테고리의 다른 글
ArrayList (0) | 2025.02.07 |
---|---|
HashSet이란?(+ TreeSet, LinkedHashSet) (0) | 2025.02.07 |
StringBuilder란? (1) | 2025.02.04 |
BufferedReader를 사용하는 이유 (0) | 2025.02.04 |
코딩 테스트 준비 (0) | 2025.02.03 |