문제
내가 작성한 정답
class Solution {
public int solution(int[] num_list) {
int answer = num_list.length>=11?0:1;
for(int i:num_list){
answer = (num_list.length>=11)? answer+ i : answer * i;
}
return answer;
}
}다른 사람들의 정답
import java.util.stream.IntStream;
class Solution {
public int solution(int[] num_list) {
IntStream stream = IntStream.of(num_list);
return num_list.length>10?stream.sum():stream.reduce(1, (a, b) -> a * b);
}
}Java Stream의 reduce 메서드는 스트림의 여러 요소를 하나의 결과로 합치는(축소하는) 기능을 수행하는 터미널 연산입니다.
특징 및 동작 원리:
- 두 가지 주요 형태가 있습니다:
reduce(BinaryOperator<T> accumulator)- 스트림 요소 두 개를 받아 하나로 합치는 함수(accumulator)를 반복 적용해서 결과를 Optional로 반환합니다.
- 빈 스트림의 경우 Optional.empty를 반환합니다.
reduce(T identity, BinaryOperator<T> accumulator)- 먼저 초기값(identity)을 준비하고, 스트림의 모든 요소와 초기값을 순서대로 함수에 적용해 누적 결과를 냅니다.
- 빈 스트림일 경우 초기값(identity) 반환합니다.
- accumulator 함수는 두 인자를 받아 하나로 합치는 연산을 수행하며, 이 함수는 결합법칙(associative)을 만족해야 합니다.
Share article