|
| 1 | +package com.learn.streams; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Optional; |
| 6 | + |
| 7 | +public class StreamsReduceExample { |
| 8 | + |
| 9 | + public static void main(String[] args) { |
| 10 | + |
| 11 | + List<Integer> numbers = List.of(10, 20, 30, 40); |
| 12 | + System.out.println(performMultiplication(numbers)); |
| 13 | + |
| 14 | + Optional<Integer> result1 = perfromMultiplicationWithoutIdentity(numbers); |
| 15 | + System.out.println(result1.isPresent()); |
| 16 | + System.out.println(result1.get()); |
| 17 | + |
| 18 | + Optional<Integer> result2 = perfromMultiplicationWithoutIdentity(new ArrayList<>()); |
| 19 | + System.out.println(result2.isPresent()); |
| 20 | + |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * <p> |
| 25 | + * Preform multiplication of the list. |
| 26 | + * </p> |
| 27 | + * @param integerList |
| 28 | + * @return |
| 29 | + */ |
| 30 | + public static int performMultiplication(List<Integer> integerList) { |
| 31 | + |
| 32 | + return integerList.stream() |
| 33 | + // num1 = 1 num2 = 10 (from Stream) => 1 * 10 result returned |
| 34 | + // num1 = 10, num2 = 20 (from Stream) => 10 * 20 result returned |
| 35 | + // num1 = 200 , num2 = 30 (from Stream) => 200 * 30 result returned |
| 36 | + // num1 = 6000 , num2 = 40 (from Stream) => 24000 result returned |
| 37 | + .reduce(1, (num1 , num2) -> num1 * num2); |
| 38 | + } |
| 39 | + |
| 40 | + public static Optional<Integer> perfromMultiplicationWithoutIdentity(List<Integer> integerList) { |
| 41 | + |
| 42 | + return integerList.stream() |
| 43 | + .reduce((num1, num2) -> num1 * num2); |
| 44 | + } |
| 45 | +} |
0 commit comments