2017-05-22 1 views
6

다음 코드는 초기화 할 필요없이 완벽하게 작동합니다.Stream.reduce (BinaryOperator <T> 누적 기)

int sum=Stream.of(2,3).reduce((Integer a,Integer b)->a+b).get(); // sum = 5 
int sum=Stream.of(2,3).reduce((Integer a,Integer b)->a*b).get(); // sum = 6 

가 어떻게 제 누산기는 새로운 합 = 0으로 초기화해야한다는 + 그렇다고 알고 있지 및 제 2 축적은 새로운 합 = 1로 초기화한다되도록 *인가?

답변

7

1 개의 인수 reduce은 아이디 값 (0 또는 1)로 시작하지 않습니다. 스트림의 값에서만 작동합니다.

Optional<T> java.util.stream.Stream.reduce(BinaryOperator<T> accumulator) 

반환이이 API 사양입니다

boolean foundAny = false; 
T result = null; 
for (T element : this stream) { 
    if (!foundAny) { 
     foundAny = true; 
     result = element; 
    } 
    else 
     result = accumulator.apply(result, element); 
} 
return foundAny ? Optional.of(result) : Optional.empty(); 
2

스트림에 하나 이상의 요소가있는 경우 ID 값이 필요하지 않습니다. 첫 번째 줄이기는 2+3을 반환하며 0+2+3과 같습니다. 두 번째 숫자는 2*3이고, 이는 1*2*3과 같습니다.

3

: 당신이 javadoc 보면, 심지어는 상응하는 코드를 보여줍니다 (선택 사양)가 감소

으로의 결과를 설명 javadoc에 해당하는 코드는 다음과 같습니다.

boolean foundAny = false; 
T result = null; 
for (T element : this stream) { 
    if (!foundAny) { 
     foundAny = true; 
     result = element; 
    } 
    else 
     result = accumulator.apply(result, element); 
} 
return foundAny ? Optional.of(result) : Optional.empty(); 

3 건 :

  1. 스트림 없음 요소 : Optional.empty를 반환()
  2. 한 요소 : 방금 전혀 축적을 적용하지 않고 요소를 돌려줍니다.
  3. 두 개 이상의 요소 : 모두에 누적기를 적용하고 결과를 반환합니다. 이 저감 방법

추가 예 :

// Example 1: No element 
Integer[] num = {}; 
Optional<Integer> result = Arrays.stream(num).reduce((Integer a, Integer b) -> a + b); 
System.out.println("Result: " + result.isPresent()); // Result: false 

result = Arrays.stream(num).reduce((Integer a, Integer b) -> a * b); 
System.out.println("Result: " + result.isPresent()); // Result: false 

// Example 2: one element 
int sum = Stream.of(2).reduce((Integer a, Integer b) -> a + b).get(); 
System.out.println("Sum: " + sum); // Sum: 2 

int product = Stream.of(2).reduce((Integer a, Integer b) -> a * b).get(); 
System.out.println("Product: " + product); // Product: 2 

// Example 3: two elements 
sum = Stream.of(2, 3).reduce((Integer a, Integer b) -> a + b).get(); 
System.out.println("Sum: " + sum); // Sum: 5 

product = Stream.of(2, 3).reduce((Integer a, Integer b) -> a * b).get(); 
System.out.println("Product: " + product); // Product: 6 
관련 문제