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


16.10 커스텀 집계(reduce())



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
package sec10.stream_reduce;
 
import java.util.Arrays;
import java.util.List;
 
public class ReductionExample {
    public static void main(String[] args) {
        List<Student> studentList = Arrays.asList(
                new Student("홍길동"92),
                new Student("신용권"95),
                new Student("감자바"88)
        );
        // 1. sum()이용
        int sum1 = studentList.stream() 
                .mapToInt(Student :: getScore)
                .sum();
        // 2. reduce(BinaryOperator<Integer> op 이용
        int sum2 = studentList.stream()
                .map(Student :: getScore)
                .reduce((a, b) -> a+b)
                .get();
        
        // 3. reduce(int identity, IntBinaryOperator op) 이용
        int sum3 = studentList.stream()
                .map(Student :: getScore)
                .reduce(0, (a, b) -> a+b);
        
        System.out.println("sum1: " + sum1);
        System.out.println("sum2: " + sum2);
        System.out.println("sum3: " + sum3);
    }
}
cs






Posted by 너래쟁이
: