티스토리 뷰

728x90
반응형

summarizingInt()는 Collectors와 함께 사용 돼 정수형 스트림에서 제목의 계산을 한번에 해주는 연산자이다.

 

물론 그중 원하는 요소를 뽑아오는 것도 얼마든지 가능한 아주 기특한 아이이다.

 

코드를 보자.

import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

public class SummarizingExample {
    public static void main(String[] args) {

        List<Integer> list = List.of(2, 3, 5, 7, 11, 13, 17, 19);

        IntSummaryStatistics statistics =
                list.stream()
                        .collect(Collectors.summarizingInt(a -> a));
//                        .collect(Collectors.summarizingInt(Integer::valueOf));
//                        .collect(Collectors.summarizingInt(Integer::intValue));

        System.out.println(statistics);
        System.out.println();
        System.out.println("Count: " + statistics.getCount());
        System.out.println("Summation: " + statistics.getSum());
        System.out.println("Average: " + statistics.getAverage());
        System.out.println("Max Value: " + statistics.getMax());
        System.out.println("Min Value: " + statistics.getMin());
        
    }
}
IntSummaryStatistics{count=8, sum=77, min=2, average=9.625000, max=19}

Count: 8
Summation: 77
Average: 9.625
Max Value: 19
Min Value: 2

2부터 19사이의 소수를 이용해 개수를 세고 더하고 평균을 내고 최댓값과 최솟값을 찾은 것을 확인할 수 있다.

 

추가로 아래 주석처리된 메서드 레퍼런스도 동일한 기능을 한다.

 

여기서 사용된 IntSummaryStatistics는 처음부터 스트림과 함께 사용하기 위해 만들어진 자료형이며

 

{개수(long), 합(long), 평균(double), 최대(int), 최소(int)}값을 각각 저장한다.

 

마지막으로 summarizingLong(), summarizingDouble() 등의 메서드도 존재한다.

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함