
for문이나 Iterator를 사용for문, Iterator → 외부에서 직접 요소를 꺼내와 처리스트림은 여러 단계로 연결 가능 → 이를 스트림 파이프라인이라 함
중간 처리: 필터링, 매핑, 정렬 등
최종 처리: 반복, 집계(카운트, 합계, 평균 등)
주의: 최종 처리가 없으면 스트림은 동작하지 않음
메소드 체이닝 패턴을 이용하면 코드가 간결해짐
java.util.stream 패키지 제공BaseStreamStream, IntStream, LongStream, DoubleStreamStream<Product> stream = list.stream();
stream.forEach(p -> System.out.println(p));
Collection.stream()Collection.parallelStream()Arrays.stream(T[])Stream.of(T[])String[] arr = {"a", "b", "c"};
Stream<String> stream = Arrays.stream(arr);
IntStream.range(start, end) → end 불포함IntStream.rangeClosed(start, end) → end 포함IntStream.range(1, 5).forEach(System.out::print); // 1234
IntStream.rangeClosed(1, 5).forEach(System.out::print); // 12345
Path path = Paths.get("data.txt");
Stream<String> stream = Files.lines(path, Charset.defaultCharset());
stream.forEach(System.out::println);
stream.close();
Files.list(Path) → 디렉토리 내 경로 스트림Random.ints(), Random.longs(), Random.doubles() → 랜덤 수 스트림distinct(): 중복 제거
filter(): 조건에 맞는 요소만 걸러냄
Stream.filter(Predicate<T>)IntStream.filter(IntPredicate)LongStream.filter(LongPredicate)DoubleStream.filter(DoublePredicate)Predicate<T>: boolean test(T t)IntPredicate: boolean test(int value)LongPredicate: boolean test(long value)DoublePredicate: boolean test(double value)map(Function<T,R>)mapToInt(ToIntFunction<T>)mapToLong(ToLongFunction<T>)mapToDouble(ToDoubleFunction<T>)asLongStream() → int → longasDoubleStream() → int/long → doubleboxed() → 기본 타입 → Wrapper 클래스List<String> list = Arrays.asList("a b c", "d e f");
list.stream()
.flatMap(str -> Arrays.stream(str.split(" ")))
.forEach(System.out::println);
Stream<T> sorted() → 기본 Comparable 기준 정렬Stream<T> sorted(Comparator<T>) → 지정된 Comparator 기준 정렬IntStream.sorted(), LongStream.sorted(), DoubleStream.sorted() → 오름차순 정렬Comparable을 구현해야 sorted() 사용 가능Comparator.reverseOrder()studentList.stream()
.sorted((s1, s2) -> Integer.compare(s1.getScore(), s2.getScore()))
.forEach(System.out::println);
forEach(Consumer<T> action)forEachOrdered(Consumer<T> action)List<String> list = Arrays.asList("a", "b", "c");
list.stream().forEach(System.out::println);
boolean allMatch(Predicate<T>)trueboolean anyMatch(Predicate<T>)trueboolean noneMatch(Predicate<T>)trueList<Integer> list = Arrays.asList(2, 4, 6);
boolean result = list.stream().allMatch(n -> n % 2 == 0);
System.out.println(result); // true
long count()Optional<T> max(Comparator<T>)Optional<T> min(Comparator<T>)OptionalDouble average()sum() (IntStream, LongStream, DoubleStream 전용)IntStream stream = IntStream.of(1, 2, 3, 4, 5);
int sum = stream.sum();
System.out.println(sum); // 15
reduce() 메소드를 이용해 직접 정의한 방법으로 집계 가능Optional<T> reduce(BinaryOperator<T> accumulator)T reduce(T identity, BinaryOperator<T> accumulator)List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// 합계 구하기 (초기값 0)
int sum = list.stream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum); // 15
Collectors.toList()Collectors.toSet()Collectors.toMap(keyMapper, valueMapper)Collectors.joining(delimiter)Collectors.groupingBy(Function<T,K>) → 그룹핑Collectors.partitioningBy(Predicate<T>) → 조건에 따라 분할List<String> names = Arrays.asList("Kim", "Lee", "Park");
// 리스트로 수집
List<String> result = names.stream()
.filter(n -> n.length() >= 3)
.collect(Collectors.toList());
System.out.println(result); // [Kim, Lee, Park]
parallelStream() → 컬렉션에서 병렬 스트림 생성stream().parallel() → 기존 스트림을 병렬 스트림으로 변환List<String> list = Arrays.asList("a", "b", "c", "d");
// 병렬 처리 (순서 보장 안 됨)
list.parallelStream().forEach(System.out::println);
// 순서 보장 병렬 처리
list.parallelStream().forEachOrdered(System.out::println);