중간연산과는 다르게, 최종연산은 스트림의 요소를 소모해서 결과를 만들어낸다.
따라서 최종 연산 후에는 스트림이 닫히게 되고 더 이상 사용할 수 없다.
forEach()
void forEach(Consumer<? super T> action)
스트림의 요소를 출력할 때 사용한다.
allMatch() , anyMatch() , noneMatch() , findFirst() , findAny()
// 지정된 조건에 모든 요소가 일치하는지 확인
boolean allMatch (Predicate<? super T> predicate)
// 지정된 조건에 일부 요소가 일치하는지 확인
boolean anyMatch (Predicate<? super T> predicate)
// 지정된 조건에 어떤 요소도 일치하지 않는지 확인
boolean noneMatch (Predicate<? super T> predicate)
// 조건에 일치하는 첫 번째 것을 반환
Optional<T> findFirst()
// 병렬 스트림인 경우에는 findFirst() 대신 findAny() 이용
Optional<T> findAny()
findFirst()와findAny()는, 스트림의 요소가 없을 때는 비어잇는Optional객체를 반환한다.
// 총점이 100점 이하인 학생이 있으면 true 없으면 false 반환
boolean noFailed = stuStream.anyMatch(s->s.getTotalScore() <=100);
// 위의 조건에 일치하는 첫 번째 학생
Optional<Student> stu = stuStream.filter(s->s.getTotalScore() <= 100).findfirst();
Optional<Student> stu = parallelStream.filter(s->s.getTotalScore() <= 100).findAny();
reduce()
// 초기값 identity와 스트림의 첫 번째 요소로 연산 시작
T reduce(T identity, BinaryOperator<T> accumulator)
// 처음 두 요소를 가지고 연산 시작
Optional<T> reduce(BinaryOperator<T> accumulator)
스트림의 요소를 줄여나가면서 연산을 수행하고 최종 결과를 반환한다.
// .count()
int count = intStream.reduce(0, (a,b)->a+1);
// .sum()
int sum = intStream.reduce(0, (a,b)->a+b);
// .max()
int max = intStream.reduce(Integer.MIN_VALUE, (a,b)->a>b?a:b);
// .min()
int min = intStream.reduce(Integer.MAX_VALUE, (a,b)->a<b?a:b);
기본형 스트림에 대해
count(),sum(),average(),max(),min()이라는 메서드가 있다.따라서 기본형 스트림으로 변환해 연산하거나, 위의
reduce()혹은 아래에서 나오는collect()를 사용해 통계정보를 얻는다.
collect()
Object colloct(Collector collector) // Collecor를 구현한 클래스의 객체를 매개변수로 사용
스트림을 컬렉션과 배열로 변환.
// List로 변환
List<String> names = stuStream.map(Student::getName).collect(Collectors.toList());
// 컬렉션으로 저장
ArrayList<String> list = names.stream().collect(Collectors.toCollection(ArrayList::new));
// Map으로 저장 ( key, value로 지정해줘야함 )
Map<String, Person> map = personStream.collect(Collectors.toMap(p->p.getRegId(), p->p));
// 배열로 저장
Student[] stuNames = studentStream.toArray(Student[]::new); // 매개변수 지정해줘야함
Object[] stuNames = studentStream.toArray(); // 매개변수 지정하지 않으면 반환 타입을 Object로 설정해야함