**집계(Aggregate)**는 최종 처리 기능이며, 요소들을 처리한 뒤
sum()
/count()
/average()
/max()
/min()
등과 같이 하나의 값으로 산출하는 것을 말한다. → 대량의 데이터를 가공해서 축소하는 리덕션(Reduction)이라고 볼 수 있다.
집계 메서드에서는 리턴값으로 java.util 패키지의 Optional, OptionalDouble, OptionalInt, OptionalLong 클래스를 리턴한다. 이 객체에서 값을 얻기 위해서는 get()
/ getAsDouble()
/ getAsInt()
/ getAsLong()
을 호출하면 된다.
public static int[] intArr = {1, 2, 3, 4, 5};
long cnt = Arrays.stream(intArr)
.filter(n -> n%2 == 0)
.count();
System.out.println(cnt); // 2
long sum = Arrays.stream(intArr)
.filter(n -> n%2 == 0)
.sum();
System.out.println(sum); // 6
double avg = Arrays.stream(intArr)
.filter(n -> n%2 == 0)
.average()
.getAsDouble();
System.out.println(avg); // 3.0
int max = Arrays.stream(intArr)
.filter(n -> n%2 == 0)
.max()
.getAsInt();
int min = Arrays.stream(intArr)
.filter(n -> n%2 == 0)
.min()
.getAsInt();
System.out.println(max + " & " + min); // 4 & 2