📚 4장. 스트림(Stream) 고급 최종 연산 정리
1. forEach()
설명: 각 요소에 대해 주어진 작업을 수행합니다.
Stream.of("A", "B", "C")
.forEach(System.out::println);
코드 분석:
Stream.of("A", "B", "C")
: 스트림 생성forEach(System.out::println)
: 각 요소를 콘솔에 출력
실행 결과:
A
B
C
2. collect()
설명: 스트림의 요소들을 모아 List, Set 등 컬렉션으로 변환합니다.
List<String> result = Stream.of("a", "b", "c")
.collect(Collectors.toList());
코드 분석:
Stream.of("a", "b", "c")
: 문자열 스트림 생성collect(Collectors.toList())
: 결과를 리스트로 수집
실행 결과: [a, b, c]
📦 보조 예시: joining()
String joined = Stream.of("Java", "Stream", "Collect")
.collect(Collectors.joining(" "));
System.out.println(joined);
코드 분석:
Collectors.joining(" ")
: 공백 기준으로 문자열을 연결
실행 결과: Java Stream Collect
📦 보조 예시: groupingBy()
Map<Integer, List<String>> grouped = Stream.of("a", "bb", "ccc")
.collect(Collectors.groupingBy(String::length));
코드 분석:
Collectors.groupingBy(String::length)
: 문자열 길이로 그룹핑
실행 결과: {1=[a], 2=[bb], 3=[ccc]}
3. count()
설명: 요소의 개수를 반환합니다.
long count = Stream.of("apple", "banana", "cherry")
.filter(s -> s.contains("a"))
.count();
코드 분석:
filter(s -> s.contains("a"))
: 'a'를 포함하는 요소 필터링count()
: 조건을 만족하는 요소 개수 반환
실행 결과: 3
4. toArray()
설명: 스트림의 요소들을 배열로 변환합니다.
String[] array = Stream.of("one", "two", "three")
.toArray(String[]::new);
코드 분석:
toArray(String[]::new)
: 스트림을 String 배열로 변환
실행 결과: [one, two, three]
5. min() / max()
설명: 최소값 또는 최대값을 Optional로 반환합니다.
Optional<Integer> max = Stream.of(10, 30, 20)
.max(Comparator.naturalOrder());
max.ifPresent(System.out::println);
코드 분석:
max(Comparator.naturalOrder())
: 자연 순서 기준 최대값 반환ifPresent(System.out::println)
: 값이 존재할 때 출력
실행 결과: 30
6. reduce()
설명: 스트림의 요소를 하나의 값으로 누적하여 반환합니다.
int sum = Stream.of(1, 2, 3, 4)
.reduce(0, Integer::sum);
System.out.println(sum);
코드 분석:
reduce(0, Integer::sum)
: 누산기로 전체 합계 계산
실행 결과: 10
📦 보조 예시: 문자열 누적
String combined = Stream.of("Java", "Stream", "Reduce")
.reduce("", (a, b) -> a + " " + b);
System.out.println(combined);
코드 분석:
reduce("", (a, b) -> a + " " + b)
: 공백을 사이에 두고 문자열 연결
실행 결과: Java Stream Reduce
📦 보조 예시: Optional 최대값
Optional<Integer> max = Stream.of(3, 5, 9, 1)
.reduce(Integer::max);
max.ifPresent(System.out::println);
코드 분석:
reduce(Integer::max)
: 최대값을 Optional로 반환ifPresent()
: 존재할 경우만 출력
실행 결과: 9
0 댓글