map, mapToInt, mapToDouble, filter, sorted,distinct, limit, skip, peek, flatMapforEach, forEachOrdered, collect, reduce, sum,count, average, min, max, anyMatch, allMatch,noneMatch, findFirst, findAny값 변환 (문자열 → 숫자, 숫자 → 제곱 등)
Arrays.stream(new String[]{"1","2","3"})
.mapToInt(Integer::parseInt)
.forEach(System.out::println);
// 1 2 3
조건 통과한 값만 남기기
IntStream.range(1, 10)
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
// 2 4 6 8
Stream.of(5, 1, 2, 5, 3)
.distinct()
.sorted()
.forEach(System.out::println);
// 1 2 3 5
IntStream.rangeClosed(1, 10)
.skip(3)
.limit(4)
.forEach(System.out::println);
// 4 5 6 7
Stream.of("A","B","C").forEach(System.out::println);
// 순서 보장X (병렬일 경우)
// A B C
Stream.of("A","B","C").forEachOrdered(System.out::println);
// 순서 보장
// A B C
누적 처리
int sum = IntStream.of(1,2,3,4).reduce(0, (a,b) -> a+b);
// 10
컬렉션/문자열로 수집
List<String> list = Stream.of("a","b","c").collect(Collectors.toList());
String joined = Stream.of("a","b","c").collect(Collectors.joining(","));
// joined = "a,b,c"
boolean anyEven = IntStream.of(1,3,5,8).anyMatch(n -> n % 2 == 0); // true
boolean allEven = IntStream.of(2,4,6).allMatch(n -> n % 2 == 0); // true
boolean noneNegative = IntStream.of(1,2,3).noneMatch(n -> n < 0); // true
OptionalInt first = IntStream.range(1, 10).findFirst(); // 1
OptionalInt any = IntStream.range(1, 10).findAny(); // (병렬 시 임의 값)
중간 과정 디버깅
Stream.of("a","b","c")
.peek(s -> System.out.println("DEBUG: " + s))
.map(String::toUpperCase)
.forEach(System.out::println);
orElse(default) : 값이 없으면 기본값 반환orElseThrow() : 값이 없으면 예외 발생int max = IntStream.empty().max().orElse(-1);
int mustMax = IntStream.empty().max().orElseThrow();
int ↔ Integer 변환 시 성능 저하 (박싱/언박싱 오버헤드)구분 Stream for문
가독성 선언적, 파이프라인 직관적, 단순
성능 오버헤드 있음 기본형 직접 연산
제어 break/continue 불편 제어문 쉬움
병렬 처리 .parallelStream() 가능 직접 구현 필요
List<Integer> nums = List.of(10, 15, 20);
nums.stream()
.map(n -> n % 2 == 0 ? n * 2 : n * 3)
.forEach(System.out::println);
// 20 45 40