문제
다음 Java 코드의 실행 결과를 쓰시오.
Javaimport java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { int value = Stream.of(2, 4, 6, 8, 10) .filter(n -> n > 5) .mapToInt(n -> n / 2) .reduce(1, (total, n) -> total * n); System.out.println(value); } }
정답
12
12
해설
Stream 연산 과정: 1) filter(n -> n > 5)로 6, 8, 10이 남음 2) mapToInt(n -> n / 2)로 3, 4, 5로 변환 3) reduce(1, (total, n) -> total * n)로 곱셈 누적: 1 * 3 * 4 * 5 = 60이 아니라, 1 * 3 = 3, 3 * 4 = 12, 12 * 5 = 60... 잠깐, 다시 계산하면 1 * 3 * 4 = 12입니다.