1. Collections & 정렬
List 정렬
// 기본 정렬 (오름차순)
Collections.sort(list);
list.sort(null);
// 내림차순
Collections.sort(list, Collections.reverseOrder());
list.sort(Collections.reverseOrder());
// 커스텀 정렬
list.sort((a, b) -> a - b); // 오름차순
list.sort((a, b) -> b - a); // 내림차순
list.sort(Comparator.comparingInt(Person::getAge)); // 객체 정렬
// 배열 정렬
Arrays.sort(arr);
Arrays.sort(arr, Collections.reverseOrder()); // Integer[] 필요
유용한 Collection 메서드
// 최대/최소값
Collections.max(list);
Collections.min(list);
// 빈도수
Collections.frequency(list, element);
// 역순
Collections.reverse(list);
// 채우기
Collections.fill(list, value);
2. String 처리
필수 String 메서드
// 변환
str.toCharArray(); // char 배열로
str.charAt(index); // 특정 인덱스 문자
str.substring(start, end); // 부분 문자열
str.toLowerCase() / str.toUpperCase();
// 검색
str.indexOf("sub"); // 첫 번째 위치
str.lastIndexOf("sub"); // 마지막 위치
str.contains("sub"); // 포함 여부
str.startsWith("pre") / str.endsWith("suf");
// 수정
str.replace("old", "new"); // 모두 교체
str.replaceAll("[0-9]", ""); // 정규식 교체
str.trim(); // 앞뒤 공백 제거
str.split(" "); // 분할하여 배열로
// 비교
str.equals(other);
str.equalsIgnoreCase(other);
str.compareTo(other); // 사전순 비교
StringBuilder (문자열 조작 시 필수)
StringBuilder sb = new StringBuilder();
sb.append("text");
sb.insert(index, "text");
sb.delete(start, end);
sb.reverse(); // 문자열 뒤집기
sb.toString(); // String으로 변환
3. Stream API
기본 Stream 연산
// 필터링
list.stream().filter(x -> x > 0).collect(Collectors.toList());
// 매핑
list.stream().map(x -> x * 2).collect(Collectors.toList());
list.stream().mapToInt(Integer::intValue).sum(); // int로 변환 후 합
// 정렬
list.stream().sorted().collect(Collectors.toList());
list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
// 중복 제거
list.stream().distinct().collect(Collectors.toList());
// 개수, 합, 평균
long count = list.stream().count();
int sum = list.stream().mapToInt(Integer::intValue).sum();
double avg = list.stream().mapToInt(Integer::intValue).average().orElse(0);
// 최대/최소
Optional<Integer> max = list.stream().max(Integer::compare);
Optional<Integer> min = list.stream().min(Integer::compare);
유용한 Collectors
// groupingBy (그룹화)
Map<Integer, List<String>> grouped = list.stream()
.collect(Collectors.groupingBy(String::length));
// counting
Map<String, Long> counted = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// joining
String joined = list.stream().collect(Collectors.joining(", "));
// toSet
Set<Integer> set = list.stream().collect(Collectors.toSet());
4. 자료구조 활용
HashMap
Map<String, Integer> map = new HashMap<>();
map.put(key, value);
map.get(key); // 없으면 null
map.getOrDefault(key, 0); // 없으면 기본값
map.containsKey(key);
map.containsValue(value);
map.remove(key);
// 반복
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
}
// 값 업데이트
map.merge(key, 1, Integer::sum); // 있으면 더하고 없으면 1
map.compute(key, (k, v) -> v == null ? 1 : v + 1);
HashSet
Set<Integer> set = new HashSet<>();
set.add(element);
set.remove(element);
set.contains(element);
set.size();
// 집합 연산
set1.addAll(set2); // 합집합
set1.retainAll(set2); // 교집합
set1.removeAll(set2); // 차집합
Stack & Queue
// Stack
Stack<Integer> stack = new Stack<>();
stack.push(element);
stack.pop();
stack.peek(); // 제거하지 않고 확인
stack.isEmpty();
// Queue
Queue<Integer> queue = new LinkedList<>();
queue.offer(element); // 추가
queue.poll(); // 제거하며 반환
queue.peek(); // 확인만
PriorityQueue (힙)
// 최소 힙 (기본)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// 최대 힙
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
// 커스텀 정렬
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
5. 유용한 유틸리티
Math 클래스
Math.max(a, b) / Math.min(a, b);
Math.abs(x); // 절대값
Math.pow(base, exp); // 거듭제곱
Math.sqrt(x); // 제곱근
Math.ceil(x) / Math.floor(x) / Math.round(x);
형변환
// String to int
int num = Integer.parseInt("123");
Integer num = Integer.valueOf("123");
// int to String
String str = String.valueOf(123);
String str = Integer.toString(123);
String str = "" + 123;
// char to int
int num = Character.getNumericValue('5'); // 5
int num = '5' - '0'; // 5
배열 관련
// 배열 복사
int[] copy = Arrays.copyOf(original, length);
int[] copy = Arrays.copyOfRange(original, from, to);
// 배열을 List로
List<Integer> list = Arrays.asList(1, 2, 3);
List<Integer> list = new ArrayList<>(Arrays.asList(arr));
// List를 배열로
Integer[] arr = list.toArray(new Integer[0]);
int[] arr = list.stream().mapToInt(i -> i).toArray();
// 2차원 배열 정렬
Arrays.sort(arr, (a, b) -> a[0] - b[0]); // 첫 번째 원소 기준
6. 코딩테스트 꿀팁
입출력 최적화
// BufferedReader (빠른 입력)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line);
int n = Integer.parseInt(st.nextToken());
// StringBuilder (빠른 출력)
StringBuilder sb = new StringBuilder();
sb.append(result).append("\n");
System.out.print(sb.toString());
자주 쓰는 패턴
// 숫자 자릿수 구하기
int digits = (int)(Math.log10(n)) + 1;
// 팰린드롬 체크
String reversed = new StringBuilder(str).reverse().toString();
boolean isPalindrome = str.equals(reversed);
// 소수 판별
boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
// 최대공약수/최소공배수
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}












