본문 바로가기

하../java

스트림의 최종연산

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

기본으로 직렬스트림으로 처리하는데 병렬로 처리할경우 여러 스레드가 함께 하기때문에 순서 보장이 안됨

IntStream.range(1,10).parallel().forEach(System.out::print); - 918273645
뒤죽박죽 출력이됨 (순서보장X)
IntStream.range(1,10).parallel().forEachOrdered(System.out::print - 123456789
로 해결 순서보장이 해결

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

 

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

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

Optional<T> findFirst() 
null일수도 있기 때문에 Optional 사용 첫번째 요소를 반환 순차 스트림에 사용
Optional<T> findAny()
null일수도 있기 때문에 Optional 아무거나 하나를 반환. 병렬 스트림에 사용
Optional<Student> result = stuStream.filter(s->s.getTotalScore() <=100).findFirst();
필터와 함께 사용함 조건에 맞는(s->s.getTotalScore() <=100) 첫번째 요소 반환
Optional<Student> result = parallelStream.filter(s->s.getTotalScore() <=100).findAny();
필터와 함께 사용함 조건에 맞는(s->s.getTotalScore() <=100) 여러 요소중에 먼저 발견하면 반환

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

Optional<T> reduce(BinaryOperator<T> accmulator)
Optional<T> reduce(T identiti, BinaryOperator<T> accumulator)

identity - 초기값
accumulator - 이전 연산결과와 스트림의 요소에 수행할 연산
// 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 a = identity;
for(int b : stream)
a = 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()
String[] strArr = {
			"Inheritance", "Java", "Lambda", "stream",
			"OptionalDouble", "IntStream", "count", "sum"
		};
        
        // 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);
		System.out.println("sum="+sum);
		System.out.println("max="+ max.getAsInt());
		System.out.println("min="+ min.getAsInt());
        
 결과
count=8
sum=58
max=14
min=3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'하.. > java' 카테고리의 다른 글

ch14 Optional<T>  (0) 2021.12.26
ch14 스트림의 중간연산2  (0) 2021.12.26
ch14 스트림의 중간연산  (0) 2021.12.26
ch14 스트림의 연산  (0) 2021.12.26
ch14 스트림 만들기  (0) 2021.12.26