JAVA chapter16. 스트림과 병렬처리. 


16.9 기본 집계(sum(), count(), average(), max(), min())

16.9.1 스트림이 제공하는 기본 집계


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
31
32
33
34
35
36
37
38
39
40
41
42
package sec09.stream_aggregate;
 
import java.util.Arrays;
 
public class AggregateExample {
    public static void main(String[] args) {
        long count = Arrays.stream(new int[] {12345})
            .filter(n -> n%2==0)
            .count();
        System.out.println("2의 배수 개수: " + count);
        
        long sum = Arrays.stream(new int[] {12345})
            .filter(n -> n%2==0)
            .sum();
        System.out.println("2의 배수의 합: " + sum);
        
        double avg = Arrays.stream(new int[] {12345})
            .filter(n -> n%2==0)
            .average() // OptionalDouble로 리턴하기 때문에 getAsDouble() 메소드를 사용해야함
            .getAsDouble();
        System.out.println("2의 배수의 평균: " + avg);
        
        int max = Arrays.stream(new int[] {12345})
            .filter(n -> n%2==0)
            .max() //
            .getAsInt();
        System.out.println("최대값: " + max);
        
        int min = Arrays.stream(new int[] {12345})
            .filter(n -> n%2==0)
            .min() //
            .getAsInt();
        System.out.println("최소값: " + min);
        
        int first = Arrays.stream(new int[] {12345})
            .filter(n -> n%3==0)
            .findFirst() //
            .getAsInt();
        System.out.println("첫번째 3의 배수: " + first);
    }
}
 
cs


16.9.2 Optional 클래스

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package sec09.stream_aggregate;
 
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalDouble;
 
public class OptionalExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        
        /*//예외 발생(java.util.NoSuchElementException)
        double avg = list.stream()
            .mapToInt(Integer :: intValue)
            .average()    
            .getAsDouble(); 
        */
        
        //방법1
        OptionalDouble optional = list.stream()
            .mapToInt(Integer :: intValue)
            .average();    
        if(optional.isPresent()) { //
            System.out.println("방법1_평균: " + optional.getAsDouble());
        } else {
            System.out.println("방법1_평균: 0.0");
        }
        
        //방법2
        double avg = list.stream()
            .mapToInt(Integer :: intValue)
            .average()
            .orElse(0.0); //
        System.out.println("방법2_평균: " + avg);
        
        list.add(2);
        list.add(4);
        //방법3
        list.stream()
            .mapToInt(Integer :: intValue)
            .average() // ifPresent : 값이 있을때만 실행해라.
            .ifPresent(a -> System.out.println("방법3_평균: " + a)); //
    }
}
 
cs



Posted by 너래쟁이
: