JAVA4_11_스트림의 최종 연산1
최종 연산
- ✨반환 : int, boolean, Optional....
-
forEachOrdered()
: 병렬 스트림으로 처리할 때 순서 유지 기능 -
Optional<T>
: 작업 결과를 래퍼클래스 객체에 담아 준다. -
findAny()
: 병렬 스트림,filter(조건)
에 맞는 요소 중 아무거나 하나 반환 -
findFirst()
: 직렬 스트림,filter(조건)
에 맞는 요소 중 첫번째 요소 반환 -
allMatch()
<->noneMatch()
-
✨✨✨
reduce()
:sum()
,count()
등에 이것이 쓰인다.?? -
✨✨✨
collect()
: reduce()를 이용하여 그룹작업을 한다.
스트림의 모든 요소에 지정된 작업 수행
forEach()
void forEach(Consumer<? super T> action)
- 병렬스트림인 경우, 순서가 보장되지 않음
forEachOrdered()
void forEachOrdered(Consumer<? super T> action)
- 병렬스트림인 경우에도 순서가 보장됨
sequential()
: 직렬 스트림으로. 디폴트parallel()
: 병렬 스트림으로
조건 검사
allMatch()
boolean allMatch(Predicate<? super T> predicate)
- 모든 요소가 조건을 만족시키면
true
anyMatch()
boolean anyMatch(Predicate<? super T> predicate)
- 한 요소라도 조건을 만족시키면
true
예)
boolean hasFailedStu = stuStream.anyMatch(s->s.getTotalScore()<=100); //낙제자가 있는지?
//100 이하인 한 사람이라도 있으면 true
noneMatch()
boolean noneMatch(Predicate<? super T> predicate)
- 모든 요소가 조건을 만족시키지 않으면
true
allMatch()
와 반대!!
조건에 일치하는 요소 찾기
findFirst()
Optional<T> findFirst()
- ✨✨
Optional<T>
: 결과가null
일 수 있어서 - 첫번째 요소 반환
- 순차 스트림에 사용
- 병렬 스트림에도 사용 가능!
findAny()
Optional<T> findAny()
- ✨✨
Optional<T>
: 결과가null
일 수 있어서 - 아무거나 하나 반환
- 병렬 스트림에 사용 : 여러 스트림에서 동시에 찾기
예)
누적연산 수행
✨✨reduce()
- 스트림의 요소를 하나씩 줄여가며 누적연산(accumulator) 수행
- 사실 스트림의 최종연산은 이 reduce()로 만들어졌다!!
Optional <T> reduce(BinaryOperator<T> accumulator) T reduce(T identity, BinaryOperator<T> accumulator)
- ✨✨
Optional<T>
: 결과가null
일 수 있어서 identity
: 초깃값, 스트림에 요소가 없다면 identity 반환accumulator
: 이전 연산결과의 스트림의 요소에 수행할 연산
U reduce(U identity, BiFunction<U,T,U> accumulator, BinaryOperator<U> combine)
combiner
: 병렬처리한 결과를 합치는 데 사용할 연산(병렬 스트림)
예)
ex14_09
📢📢 주의
- 📢📢 주의깊게 보기
Optional<String> sWord1 = Stream.of(strArr);
-
✨여러 방식에 따라 받는 변수도 다르다는 점
-
람다식과 메소드참조를 자유자재로 변경시키기!!
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Ex14_09 {
public static void main(String[] args) {
String[] strArr = {
"Inheritance", "Java", "Lambda", "stream",
"OptionalDouble", "IntStream", "count", "sum"
};
// Stream<String> strStream = Stream.of(strArr);
// strStream.forEach(System.out::println);
Stream.of(strArr).forEach(System.out::println);
System.out.println("---------");
Stream.of(strArr).parallel().forEach(System.out::println);
System.out.println("---------");
Stream.of(strArr).parallel().forEachOrdered(System.out::println);
System.out.println("---------");
boolean noEmptyStr = Stream.of(strArr).noneMatch(s->s.length()==0);
//길이가==0 인 문자열이 하나라도 있으면 false
System.out.println("noEmptyStr= "+noEmptyStr);
//????????Optional이 스트림을 받..지 근데 아래처럼 Stream.of도 되네
Optional<String> sWord1 = Stream.of(strArr).
filter(s->s.charAt(0)=='s').findFirst();
Optional<String> sWord2 = Stream.of(strArr).parallel().
filter(s->s.charAt(0)=='s').findAny();
System.out.println("sWord1= "+sWord1.get());
System.out.println("sWord2= "+sWord2.get()); //sum 또는 stream 이 나옴
//Stream<String> -> Stream<Integer>로 변환
Stream<Integer> is = Stream.of(strArr).map(String::length);
//성능 향상을 위해 ***기본형 스트림으로 변환한다.
//Stream<String> -> IntStream으로 변환. ***mapToInt()
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);
//Math::max(),min() // Integer::sum(),max(),min()
int count = intStream1.reduce(0, (a,b)->a+1);
int sum1 = intStream2.reduce(0, (a,b)->a+b);
// int sum2 = intStream2.reduce(0, Integer::sum);
// OptionalInt max1 = intStream3.reduce((a,b)->a>=b? a:b);
OptionalInt max2 = intStream3.reduce(Integer::max);
// OptionalInt max3 = intStream3.reduce(Math::max);
//OptionalInt max = IntStream.empty().reduce(Math::max);
// int max_1 = intStream3.reduce(0, (a,b)->a>=b? a:b);
// int max_2 = intStream3.reduce(0, Integer::max);
// int max_3 = intStream3.reduce(0, Math::max);
OptionalInt min = intStream4.reduce(Integer::min);
System.out.println("count= "+count);
System.out.println("sum1= "+sum1);
// System.out.println("sum2= "+sum2);
// System.out.println("max1= "+max1.getAsInt());
System.out.println("max2= "+max2.orElse(0));
// System.out.println("max3= "+max3.orElseGet(()->0));
// //아래는 int기 때문에 따로 get()이 필요없다!!
// System.out.println("max_1= "+max_1);
// System.out.println("max_2= "+max_2);
// System.out.println("max_3= "+max_3);
System.out.println("min= "+min.getAsInt());
}
}
Inheritance
Java
Lambda
stream
OptionalDouble
IntStream
count
sum
---------
IntStream
OptionalDouble
sum
count
Java
Inheritance
Lambda
stream
---------
Inheritance
Java
Lambda
stream
OptionalDouble
IntStream
count
sum
---------
noEmptyStr= true
sWord1= stream
sWord2= sum
count= 8
sum1= 58
max2= 14
min= 3
Ref
Author And Source
이 문제에 관하여(JAVA4_11_스트림의 최종 연산1), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@lecharl/JAVA411저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)