
프로그래밍 언어
Java Streams APIJava Streams API
Java Streams API(Java 8+)는 컬렉션 데이터를 선언적으로 처리하는 함수형 파이프라인이다. 중간 연산과 최종 연산을 체이닝하여 지연 평가(lazy evaluation)로 효율적으로 동작한다.
스트림 생성
java
// 컬렉션에서
List<String> list = List.of("a", "b", "c");
Stream<String> s1 = list.stream();
Stream<String> s2 = list.parallelStream(); // 병렬 스트림
// 직접 생성
Stream.of(1, 2, 3);
IntStream.range(0, 10);
IntStream.rangeClosed(1, 5);
Stream.iterate(0, n -> n + 1).limit(10);
Stream.generate(Math::random).limit(5);중간 연산 (Intermediate)
java
List<Integer> result = IntStream.rangeClosed(1, 20)
.boxed()
.filter(n -> n % 2 == 0) // 짝수만
.map(n -> n * n) // 제곱
.sorted(Comparator.reverseOrder()) // 역순 정렬
.distinct() // 중복 제거
.limit(5) // 5개만
.collect(Collectors.toList());최종 연산 (Terminal)
java
// 집계
long count = stream.count();
Optional<Integer> max = stream.max(Comparator.naturalOrder());
int sum = IntStream.of(1, 2, 3).sum();
double avg = IntStream.of(1, 2, 3).average().orElse(0);
// 수집
List<String> names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());
Map<String, List<Person>> byCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity));
// 리듀스
int product = Stream.of(1, 2, 3, 4)
.reduce(1, (a, b) -> a * b);flatMap과 peek
java
// flatMap: Stream<Stream<T>> → Stream<T>
List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4));
List<Integer> flat = nested.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
// [1, 2, 3, 4]
// peek: 디버깅용 중간 확인
list.stream()
.peek(e -> System.out.println("Before: " + e))
.filter(e -> e > 2)
.peek(e -> System.out.println("After: " + e))
.collect(Collectors.toList());
