개발 공부/Java & Spring

22. 스트림의 최종연산

빵다희 2023. 3. 26. 19:44
스트림의 최종연산
: 스트림이 제공하는 연산은 중간 연산과 최종 연산으로 분류할 수 있다.
✔️ 중간연산 : 연산결과를 스트림으로 반환하기 때문에 중간 연산을 연속해서 연결 할 수 있다.
✔️ 최종연산 : 스트림의 요소를 소모하면서 연산을 수행하므로 단 한번만 연산이 가능하다. 연산의 결과는 스트림의 요소의 합과 같은 단일 값이거나, 스트림의 요소가 담긴 배열 또는 컬렉션일 수 있다. 

forEach()
:  스트림의 요소를 소모하는 최종연산이다. 반환타입이 void이므로 스트림의 요소를 출력하는 용도로 많이 사용된다. 
최종 연산 설명
void forEach(consumer <? super T> action)  각 요소에 지정된 작업 수행 (병렬 스트림의 경우 순서가 보장되지 않음)
void forEachOrdered(consumer <? super T> action) 각 요소에 지정된 작업 수행(병렬 스트림의 경우 순서가 보장됨)
/* forEach 예시 */
String[] strArr = {
                "Inheritance","Java","Lambda","stream",
                "OptionalDouble","IntStream","count","sum",
        }; 
Stream.of(strArr).forEach(System.out::println);

/*
Inheritance
Java
Lambda
stream
OptionalDouble
IntStream
count
sum
*/

 

조건검사 - allMatch(), anyMatch, noneMatch(), findFirst(), findAny()
 최종 연산 설명
boolean allMathch(predicate<T> p)  주어진 조건을 모든 요소가 만족하는지 확인
boolean anyMathch(predicate<T> p)  주어진 조건을 하나라도 만족하는지 확인
boolean noneMathch(predicate<T> p)  주어진 조건을 모두 만족하지 않는지 확인
optional<T> findFirst() 스트림의 요소 중 가장 첫번째의 요소를 반환
optional<T> findAny() 스트림의 요소 중 아무거나 하나를 반환
String[] strArr = {
                "Inheritance","Java","Lambda","stream",
                "OptionalDouble","IntStream","count","sum",
        };
/* noneMatch 예시 */
/* 스트링의 길이가 0인 것이 하나도 없을때 true / 있으면 false */
boolean noEmptyStr = Stream.of(strArr).noneMatch(s->s.length() == 0);
System.out.println(noEmptyStr); /* true */
        
/* findFirst 예시 */   
/* 첫글자가 's'로 시작하는 스트링 중 가장 첫번째 요소를 가져옴 */
Optional<String> sWord = Stream.of(strArr).filter(s->s.charAt(0)=='s').findFirst();
System.out.println(sWord.get()); /* stream */

/* 병렬 스트림인 경우에는 FindFirst()대신 findAny()를 사용해야한다.*/
Optional<Student> stu = parallelStream.filter(s->s.getTotalScore()<=100).findAny();
통계 - count(), sum(), average(), max(), min()
: 기본형 스트림이 아닌 경우에는 통계와 관련된 메서드들이 count, max, min 3개 뿐이다.
대부문의 경우 위의 메서드를 사용하기보다 기본형 스트림으로 변환하거나,  아니면 reduce()와 collect()를 사용해서 통계정보를 얻는다.
리듀싱 - reduce()
: 스트림의 요소를 줄여나가면서 연산을 수행하고 최종결과를 반환한다. 
  매개변수의 타입은 BinaryOperator<T>이다. 
Optional<T> reduce(BinarayOperator<T> accmulator)

/* 초기값(identity) : 초기값이 있는 경우에는 초기값과 스트림의 첫 번째 요소로 연산을 시작한다. */
/* 스트림 요소가 하나도 없으면 초기값이 반환된다. */
T reduce (T identity, BinarayOperator<T> accmulator)

/* combiner : 병렬 스트림에 의해 처리된 결과를 합칠 때 사용하는 것 */
U reduce (U identity, Bifunction<U,T,U> accmulator, BinarayOperator<T> combiner)
      /* reduce 예시 */

       String[] strArr = {
                "Inheritance","Java","Lambda","stream",
                "OptionalDouble","IntStream","count","sum",
        };
        
        // 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);

        int count = intStream1.reduce(0, (a,b) -> a + 1);
        int sum = intStream2.reduce(0, (a,b) -> a + b);

        OptionalInt max = intStream3.reduce(Integer::max);
        OptionalInt min = intStream4.reduce(Integer::min);

        System.out.println("count="+count);        /* 8 */
        System.out.println("sum="+sum);            /* 58 */ 
        System.out.println("max="+max.getAsInt()); /* 14 */
        System.out.println("min="+min.getAsInt()); /* 3 */

 

728x90
반응형

'개발 공부 > Java & Spring' 카테고리의 다른 글

24. Collector 구현하기  (0) 2023.03.29
23. 스트림 - collect()  (0) 2023.03.26
21. fork & join 프레임워크  (0) 2023.03.09
20. volatile  (0) 2023.03.09
19. 쓰레드의 동기화  (0) 2023.03.09