스트림의 최종 연산
최종 연산 | 설명 |
void forEach(Consumer<? super T> action) void forEachOrdered(Consumer<? super T> action) |
각 요소에 지정된 작업 수행 - 병렬스트림인 경우 순서가 보장되지 않음 - 병렬스트림인 경우에도 순서가 보장됨 |
long count() | 스트림의 요소의 개수 반환 |
Optional<T> max(Comparator<? super T> comparator) Optional<T> min(Comparator<? super T> comparator) |
스트림의 최대값/최소값을 반환 |
Optional<T> findAny() // 아무거나 하나를 반환 Optional<T> findFirst() // 첫 번째 요소를 반환 |
스트림의 요소 하나를 반환 - 병렬 스트림에 사용 - 순차 스트림에 사용 |
boolean allMatch (Predicate<? super T> predicate) boolean anyMatch (Predicate<? super T> predicate) boolean noneMatch(Predicate<? super T> predicate) |
주어진 조건을 모든 요소가 만족시키는지, 만족시키지 않는지 확인 - 모든 요소가 조건을 만족시키면 true - 한 요소라도 조건을 만족시키면 true - 모든 요소가 조건을 만족시키지 않으면 true |
Object[] toArray() A[] toArray(IntFunction<A[]> generator) |
스트림의 모든 요소를 배열로 반환 - 스트림의 모든 요소를 Object배열에 담아 반환 - 스트림의 모든 요소를 A타입의 배열에 담아 반환 |
Optional<T> reduce(BinaryOperator<T> accumulator) T reduce(T identity, BinaryOperator<T> accumulator) U reduce(U identity, BiFunction<U,T,U> accumulator, BinaryOperator<U> combiner) |
스트림의 요소를 하나씩 줄여가면서(리듀싱) 계산한다. |
R collect(Collector<T, A, R> collector) Object collect(Supplier<R> supplier, BiConsumer<R, T> accumulator, BiConsumer<R, R> combiner) |
스트림의 요소를 수집한다. 주로 요소를 그룹화하거나 분할한 결과를 컬렉션에 담아 반환하는데 사용된다. - Collector를 구현한 클래스의 객체를 매개변수로 - 잘 안쓰임 |
스트림의 모든 요소에 지정된 작업을 수행 - forEach(), forEachOrdered()
- 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
IntStream.range(1, 10).parallel().forEachOrdered(System.out::print); // 123456789
스트림을 배열로 변환 – toArray( )
Object[] toArray() // 스트림의 모든 요소를 Object배열에 담아 반환
A[] toArray(IntFunction<A[]> generator) // 스트림의 모든 요소를 A타입의 배열에 담아 반환
Student[] stuNames = studentStream.toArray(Student[]::new); // OK. x-> new Student[x]
Student[] stuNames = studentStream.toArray(); // 에러.
Object[] stuNames = studentStream.toArray(); // OK.
스트림의 요소 조건 검사 – allMatch( ), anyMatch( ), noneMatch( )
- Predicate는 반환타입이 boolean이기 때문에 allMatch( ), anyMatch( ), noneMatch( )의 반환 타입은 boolean이다.
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( )
- 결과가 null일수 있기 때문에 반환 타입이 Optional<T>이다.
- 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();
스트림에 대한 통계정보 제공 – count( ), sum( ), average( ), max( ), min( )
// Stream<T>
long count()
Optional<T> max(Comparator<? super T> comparator)
Optional<T> min(Comparator<? super T> comparator)
//IntStream
long count()
Int sum()
OptionalDouble average()
OptionalInt max()
OptionalInt min()
IntSummaryStatistics summaryStatistics()
// IntSummaryStatistics
double getAverage()
long getCount()
int getMax()
int getMin()
long getSum()
스트림의 요소를 하나씩 줄여가며 누적연산 수행 – reduce( )
- accumulator은 누적연산이란 뜻으로 어떤 방식으로 누적할지 지정할 때 사용된다.
Optional<T> reduce(BinaryOperator<T> accumulator)
T reduce(T identity, BinaryOperator<T> accumulator)
U reduce(U identity, BiFunction<U,T,U> accumulator, BinaryOperator<U> combiner)
- 초기값 identity 이 있다면 스트림의 요소가 하나도 없더라도 초기값을 반환하지만 초기값(identity)이 없다면 스트림의 요소가 하나도 없을 경우 반환 값이 null일 수 있기 때문에 Optional<T>을 반환한다.
identity - 초기값
accumulator - 이전 연산결과와 스트림의 요소에 수행할 연산
combiner - 병렬처리된 결과를 합치는데 사용할 연산(병렬 스트림)
int a = identity;
for(int b : stream)
a = a + b; // sum()
// int reduce(int identity, IntBinaryOperator op)
int count = intStream.reduce(0, (a,b) -> a + 1); // count()
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()
// OptionalInt reduce(IntBinaryOperator accumulator)
OptionalInt max = intStream.reduce((a,b) -> a > b ? a : b); // max()
OptionalInt min = intStream.reduce((a,b) -> a < b ? a : b); // min()
OptionalInt max = intStream.reduce(Integer::max); // static int max(int a, int b)
OptionalInt min = intStream.reduce(Integer::min); // static int min(int a, int b)
스트림을 배열로 변환
- 스트림을 배열로 변환 - toArray()
Object[] toArray() // 스트림의 모든 요소를 Object배열에 담아 반환
A[] toArray(IntFunction<A[]> generator) // 스트림의 모든 요소를 A타입의 배열에 담아 반환
Student[] stuNames = studentStream.toArray(Student[]::new); // OK
//Student[] stuNames = studentStream.toArray((length) -> new Student[length]); // OK
Student[] stuNames = studentStream.toArray(); // 에러
Object[] stuNames = studentStream.toArray(); // Ok
'Java' 카테고리의 다른 글
[JAVA] 네트워킹(Networking) (0) | 2024.03.14 |
---|---|
[JAVA] 스트림(Stream) API(4, Collectors, 그룹화와 분할) (0) | 2024.03.14 |
[JAVA] 스트림(Stream) API(2, 중간 연산, Optinal<T>) (0) | 2024.02.29 |
[JAVA] 스트림(Stream) API(1) (0) | 2024.02.25 |
[JAVA] 람다 표현식(Lambda Expression) (0) | 2024.01.28 |