스트림의 최종 연산 - forEach(), forEachOrdered(), allMatch(), anyMatch(), noneMatch(), findFirst(), findAny(), reduce()

이의준·2024년 6월 17일

Java

목록 보기
86/87

스트림의 모든 요소에 지정된 작업 수행 - forEach(), forEachOrdered()

void forEach(Consumer<? super T> action) // 병렬스트림인 경우 순서가 보장되지 않음
void forEachOrdered(Consumer<? super T> actoin) // 병렬스트림인 경우에도 순서가 보장됨
  • ex)
IntStream.range(1, 10).sequential().forEach(System.out::print); // 123456789
IntStream.range(1, 10).sequential().forEachOrdered(System.out::print); // 123456789
IntStream.range(1, 10).parallel().forEach(System.out::print); // 683924715 (병렬 스트림이라서 순서 보장 x)
IntStream.range(1, 10).parallel().forEachOrdered(System.out::print); // 123456789


조건 검사 - allMatch(), anyMatch(), noneMatch()

boolen allMatch (Predicate<? super T> predicate) // 모든 요소가 조건을 만족시키면 true
boolean anyMatch (Predicate<? super T> predicate) // 한 요소라도 조건을 만족시키면 true
boolean noneMatch (Predicate<? super T> predicate) // 모든 요소가 조건을 만족시키지 않으면 true
  • ex)
boolean hasFailedStu = stuStream.anyMatch(s -> s.getTotalScore() <= 100); // 낙제자가 있는가?


조건에 일치하는 요소 찾기 - findFirst(), findAny()

Optional<T> findFirst() // 첫 번째 요소를 반환, 순차 스트림에 사용
Optional<T> findAny() // 아무거나 하나를 반환. 병렬 스트림에 사용
  • ex)
Optional<Student> result = stuStream.filter(s -> s.getTotalScore() <= 100).findFirst();
Optional<Student> result = parallelStream.filter(s -> s.getTotalScore() <= 100).findAny();


스트림의 요소를 하나씩 줄여가며 누적연산 수행 - reduce()

// int reduce(int identity, IntBinaryOperator op)
int count = intStream.reduce(0, (a,b) -> a + 1);
int sum = intStream.reduce(0, (a,b) -> a + b);

int max = intStream.reduce(Integer.MIN_VALUE, (a,b) -> a > b ? a : b); // max()
int min = intStream.reduce(Integer.MAX_VALUE, (a,b) -> a < b ? a : b); // min()


0개의 댓글