Ch14-40~44. 스트림 최종연산
0. 목차
Chapter14. 람다와 스트림
Ch14 - 40. 스트림의 최종연산 : forEach()
Ch14 - 41. 스트림의 최종연산 : 조건검사
Ch14 - 42. 스트림의 최종연산 : reduce()
Ch14 - 43. 스트림의 최종연산 : reduce()의 이해
Ch14 - 44. 스트림의 최종연산 : reduce() 예제
Ch14 - 40. 스트림의 최종연산 : forEach(), forEachOrdered()
▶ forEach()
▷ 병렬 스트림인 경우 순서가 보장되지 않음
- 병렬 스트림 : 여러 쓰레드가 나눠서 작업하는 것
▶ forEachOrdered()
▷ 병렬 스트림인 경우에도 순서가 보장됨
▶ forEach()
vs forEachOrdered()
▷ sequential()
(직렬 스트림)일 때
forEach()
IntStream.range(1, 10).sequential().forEach(System.out::print); // 123456789
forEachOrdered()
IntStream.range(1, 10).sequential().forEachOrdered(System.out::print); // 123456789
▷ parallel()
(병렬 스트림)일 때
forEach()
IntStream.range(1, 10).parallel().forEach(System.out::print); // 68329714, 순서 보장X
forEachOrdered()
IntStream.range(1, 10).parallel().forEachOrdered(System.out::print); // 123456789, 순서 보장O
Ch14 - 41. 스트림의 최종연산 : 조건 검사, 일치 요소
▶ 조건 검사 : allMatch()
▷ 모든 요소가 조건을 만족시키면 true
boolean allMatch (Predicate<? super T> predicate)
▶ 조건 검사 : anyMatch()
▷ 한 요소라도 조건을 만족시키면 true
boolean anyMatch (Predicate<? super T> predicate)
▷ 예시
boolean hasFailedStu = stuStream.anyMatch(s -> s.getTotalScore() <= 60); // 60점 이하 낙제자
▶ 조건 검사 : noneMatch()
▷ 모든 요소가 조건을 만족시키지 않으면 true
boolean noneMatch (Predicate<? super T> predicate)
▶ 조건에 일치하는 요소 찾기 : findFirst()
▷ 첫 번째 요소를 반환
▷ 순차 스트림에 사용
▷ 결과가 null
일 수 있으므로 Optional<T>
사용
Optional<T> findFirst()
▷ 예시
// stuStream : 순차 스트림 → findFirst() 사용
Optional<Strudent> result = stuStream.filter(s -> s.getTotalScore() <= 100).findFirst();
▶ 조건에 일치하는 요소 찾기 : findAny()
▷ 아무거나 하나를 반환
▷ 병렬 스트림에 사용
Optional<T> findAny()
▷ 예시
// parallelStream : 병렬 스트림 → findAny() 사용
Optional<Strudent> result = parallelStream.filter(s -> s.getTotalScore() <= 100).findAny();
Ch14 - 42. 스트림의 최종연산 : reduce()
▶ reduce()
▷ 스트림의 요소를 하나 씩 줄여가며 누적 연산(accumulator) 수행
Optional<T> reduce(BinaryOperator<T> accumulator) // identity 無 → Optional로 감싸서 반환
T reduce(T identity, BinaryOperator<T> accumulator) // identity 有, 사실상 위의 코드드와 동일
U reduce(U identity, BiFunction<U, T, U> accumulator, BinaryOperator<U> combiner)
// identity : 초기값
// accumulator : 이전 연산 결과와 스트림의 요소에 수행 할 연산
// combiner : 병렬 처리 된 결과를 합치는 데 사용 할 연산(병렬 스트림)
Ch14 - 43. 스트림의 최종연산 : reduce()의 이해
▶ count()
▷ 동작 원리
// int reduce(int identity, IntBinaryOperator o)
int count = intStream.reduce(0, (a, b) -> a + 1); // 초기값 0
// 동작 원리
int a = identity; // identity = 0, 위의 람다식에서 초기값 0으로 줌
for(int b : stream)
a = a + 1;
▶ sum()
▷ 동작 원리
// int reduce(int identity, IntBinaryOperator o)
int sum = intStream.reduce(0, (a, b) -> a + b); // 초기값 0
// 동작 원리
int a = identity; // identity = 0, 위의 람다식에서 초기값 0으로 줌
for(int b : stream)
a = a + b;
▶ max()
▷ 동작 원리
// int reduce(int identity, IntBinaryOperator o)
int max = intStream.reduce(Integer.MAX_VALUE, (a, b) -> a > b ? a : b); // 초기값이 최대값
// 동작 원리
// 초기값을 최대값으로 받고, 다른 요소들과 비교하여 제일 큰 지 확인 후 반환
▶ min()
▷ 동작 원리
// int reduce(int identity, IntBinaryOperator o)
int min = intStream.reduce(Integer.MIN_VALUE, (a, b) -> a < b ? a : b); // 초기값이 최소값
// 동작 원리
// 초기값을 최소값으로 받고, 다른 요소들과 비교하여 제일 작은 지 확인 후 반환
Ch14 - 44. 스트림의 최종연산 : reduce() 예제
▶
▷ String[] 생성
String[] strArr = {
"Inheritance", "Java", "Lambda", "stream", "OptionalDouble", "IntStream", "count", "sum"
};
▷ strArr를 Stream으로 생성 후 무작위 출력
Stream.of(strArr)
.parallel() // 병렬 → 순서 유지X
.forEach(System.out::println); // forEach() : 순서 유지X
// console
IntStream
Inheritance
stream
Lambda
OptionalDouble
Java
sum
count
▷ strArr를 Stream으로 생성 후 순서대로 출력
Stream.of(strArr)
.parallel() // 병렬 → 순서 유지X
.forEachOrdered(System.out::println); // forEachOrdered() : 순서 유지O
// console
Inheritance
Java
Lambda
stream
OptionalDouble
IntStream
count
sum
▷ 문자열 길이가 0인 게 하나라도 있으면 false를 출력
boolean noEmptyStr = Stream.of(strArr)
.noneMatch(s -> s.length() == 0);
System.out.println("noEmptyStr : " + noEmptyStr);
// console
noEmptyStr : true
▷ ‘s’로 시작하는 문자열 찾기
Optional<String> sWord = Stream.of(strArr)
.filter(s -> s.charAt(0) == 's')
.findFirst();
System.out.println("sWord : " + sWord.get());
// console
sWord : stream
▷ Stream<String>
을 Stream<Intege>
으로 변환
Stream<Integer> intStream = Stream.of(strArr).map(String::length);
▷ Stream<String>
을 IntStream
(기본형 스트림)으로 변환
IntStream intStream1 = Stream.of(strArr).mapToInt(String::length);
IntStream intStream2 = Stream.of(strArr).mapToInt(String::length);
IntStream intStream3 = Stream.of(strArr).mapToInt(String::length);
IntStream intStream4 = Stream.of(strArr).mapToInt(String::length);
▷ count()
, sum()
, max()
, min()
구하기
// count : 단어 개수 세기
int count = intStream1.reduce(0, (a,b) -> a + 1);
// sum : 알파벳 개수 모두 더하기
int sum = intStream2.reduce(0, (a,b) -> a + b);
// max : 알파벳 개수 제일 많은 것
OptionalInt max = intStream3.reduce(Integer::max);
// min : 알파벳 개수 제일 적은 것
OptionalInt min = intStream4.reduce(Integer::min);
System.out.println("count : " + count);
System.out.println("sum : " + sum);
System.out.println("max : " + max.getAsInt()); // OptionalInt이기 때문에 getAsInt로 꺼내야 함
System.out.println("min : " + min.getAsInt());
// console
count : 8
sum : 58
max : 14
min : 3