Java

147. 스트림의 최종연산 - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2025. 1. 12. 18:02

1. 스트림의 최종연산 - forEach()

  • 스트림의 모든 요소에 지정된 작업을 수행 - forEach(), forEachOrdered()
void forEach(Consumer<? super T> action)	// 병렬스트림인 경우 순서가 보장되지 않음
void forEachOrdered(Consumer<? super T> action)	// 병렬스트림인 경우에도 순서가 보장됨

// sequential() - 직렬 스트림
IntStream.range(1, 10).sequential().forEach(System.out::print);		// 123456789
IntStream.range(1, 10).sequential().forEachOrdered(System.out::print);	// 123456789

// parallel() - 병렬 스트림
IntStream.range(1, 10).parallel().forEach(System.out::print);	// 635417982
IntStream.range(1, 10).parallel().forEachOrdered(System.out::print);	// 123456789

 

2. 스트림의 최종연산 - 조건 검사

  • 조건 검사 - 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();

 

3. 스트림의 최종연산 - reduce()

  • 스트림의 요소를 하나씩 줄여가며 누적연산 수행 - reduce()
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 - 초기값
// accumulator - 이전 연산결과와 스트림의 요소에 수행할 연산
// combiner - 병렬처리된 결과를 합치는데 사용할 연산(병렬 스트림)
// 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()

int a = identity;

for(int b : stream)
	a = a + b;	// sum()
	String[] strArr = {
                "Inheritance", "Java", "Lambda", "stream",
                "OptionalDouble", "IntStream", "count", "sum"
        };

        Stream.of(strArr).forEach(System.out::print);
        System.out.println();
        Stream.of(strArr).parallel().forEach(System.out::print);    // 병렬스트림 순서X
        System.out.println();
        Stream.of(strArr).parallel().forEachOrdered(System.out::print);    // 병렬스트림 순서유지
        System.out.println();

        boolean noEmptyStr = Stream.of(strArr).noneMatch(s->s.length()==0); // 문자열 길이가 0인게 하나라도 있나
        Optional<String> sWord = Stream.of(strArr)
                .filter(s->s.charAt(0)=='s').findFirst();   // 첫 문자가 s인것

        Optional<String> sWord2 = Stream.of(strArr).parallel()
                .filter(s->s.charAt(0)=='s').findAny();   // 첫 문자가 s인것 병렬 스트림

        System.out.println("noEmptyStr="+noEmptyStr);   // noEmptyStr=true
        System.out.println("sWord="+sWord);             // sWord=Optional[stream]
        System.out.println("sWord2="+sWord2);             // sWord=Optional[stream] or sWord2=Optional[sum]

        // Stream<String>을 Stream<Integer>으로 변환
        Stream<Integer> intStream0 = Stream.of(strArr).map(String::length);

        // Stream<String>을 IntStream으로 변환. 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); // count=8
        System.out.println("sum="+sum);     // sum=58
        System.out.println("max="+max.orElseGet(()->0));     // max=14
        System.out.println("min="+min.orElse(0));     // min=3
        System.out.println("min="+min.getAsInt());     // min=3