새발블로그
코딩테스트를 위한 Java 심화 본문
1. 함수형 인터페이스와 람다 표현식
Java에서는 메소드를 직접 인자로 넘길 수 없지만, 하나의 추상 메소드만 가지는 함수형 인터페이스를 이용하면 유사한 효과를 낼 수 있다.
@FunctionalInterface
public interface Runnable {
void run();
}
- 익명 클래스 방식
func(new Runnable() {
public void run() {
System.out.println("Hello");
}
});
- 람다 표현식 방식 (Java 8 이상)
func(() -> System.out.println("Hello"));
람다 기본 형태
(param) -> returnValue;
str -> str.length();
변수에 람다 저장
ToIntFunction<String> func = str -> str.length();
2. 메소드 레퍼런스
람다 표현식이 단순히 메소드 하나를 호출하는 경우, 메소드 레퍼런스로 간결하게 표현할 수 있다.
Consumer<String> c = System.out::println;
Function<String, Integer> f = String::length;
형식: 클래스명::메소드명 또는 객체::메소드명
3. 스트림 (Stream)
Stream API는 반복문을 대체해 데이터 처리 로직을 간결하게 표현할 수 있는 도구이다.
List<String> animals = List.of("rabbit", "tiger", "dog", "cat");
animals.stream()
.filter(s -> s.length() > 3)
.map(String::toUpperCase)
.sorted()
.limit(2)
.forEach(System.out::println);
스트림의 작업 흐름
- 중간 작업: filter, map, sorted, limit (계속 이어짐)
- 종결 작업: forEach, collect, count (스트림 종료)
4. 스트림 생성 방법
- 배열: Arrays.stream(arr)
- 리스트/셋: list.stream()
- 맵: map.keySet().stream(), map.entrySet().stream() 등
5. 수집(collect)과 변환
- 리스트로 변환
List<Integer> result = list.stream()
.map(String::length)
.collect(Collectors.toList());
- 그룹화
Map<Integer, List<String>> grouped = list.stream()
.collect(Collectors.groupingBy(String::length));
6. 특수 스트림 (IntStream, LongStream, DoubleStream)
int[], long[], double[] 배열에서 스트림 생성 시 아래와 같은 특수 스트림이 만들어집니다.
통계 메소드 예시
int[] arr = {1, 2, 3};
int sum = Arrays.stream(arr).sum();
int min = Arrays.stream(arr).min().getAsInt();
double avg = Arrays.stream(arr).average().getAsDouble();
일반 스트림으로 변환
List<Integer> list = Arrays.stream(arr)
.boxed()
.collect(Collectors.toList());
'Problem Solving > 개념' 카테고리의 다른 글
| 완전탐색 (Exhaustive Search) - 반복문을 활용한 접근 (2) | 2025.07.04 |
|---|---|
| 시간복잡도 (0) | 2025.07.04 |
| Java 문자열 처리 (0) | 2025.07.04 |
| 코딩테스트를 위한 Java 개요 (0) | 2025.07.04 |
| 테스트케이스 (0) | 2025.07.04 |