자바의 정석 - Stream

최준석·2022년 11월 5일
0

자바의 정석

목록 보기
6/6

Stream

14-40 스트림의 최종연산 - forEach()

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

예시)

void forEach(Consumer<? super T> action) // 병렬스트림인 경우 순서가 보장되지 않음
void forEachOrdered(Consumer<? super T> action) // 병렬스트림인 경우에도 순서가 보장됨

//기본적으로 스트림은 직렬이므로 생략가능하다
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); // 683295714 순서보장 X
IntStream.range(1, 10).parallel().forEachIOrdered(System.out::print); // 123456789

14-41 스트림의 최종연산 - 조건검사

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

예시)

boolean allMatch(Predicate<? super T> predicate) // 모든 요소가 조건을 만족시키면 true
boolean anyMatch(Predicate<? super T> predicate) // 한 요소라도 조건을 만족시키면 true
boolean noneMatch(Predicate<? super T> predicate) // 모든 요소가 조건을 만족시키지 않으면 true

boolean hasFailedStu = stuStream.anyMatch(s -> s.getTotalScore()<=100); // 낙제자가 있는지

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

예시)

Optional<T> findFirst() // 첫 번째 요소를 반환. 순차 스트림에 사용
Optional<T> findAny() // 아무거나 하나를 반환. 병렬 스트림에 사용

Optional<Student> result = stuStream.filter(s -> s.getTotalScore()<=100).findFirst();
Optional<Student> result = parallelStream.filter(s -> s.getTotalScore()<=100).findAny();

14-42, 43 스트림의 최종연산 - reduce()

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

에시)

Optional<T> reduce(BinaryOperator<T> accumulator) // 초기값이 없는 경우에는 Null이 반환될 수 있으므로 Optional로 감싸져있다
T		reduce(T identity, BinaryOperator<T> accumulator)
U		reduce(U identity, BiFunction<U, T, U> accumulator, BinaryOperator<U> combiner)

//identity - 초기값
//accumulator - 이전 연산결과와 스트림의 요소에 수행할 연산
//combiner - 병렬처리된결과를 합치는데 사용할 연산(병렬 스트림)

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

/**
int a = identity;

for(int b : streram)
	a = a + b; // sum()
**/
int sum = intStream.reduce(0, (a,b) -> a+b); // sum()
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()
profile
Back-End Web Developer

0개의 댓글