Skip to content

Commit 7cd3909

Browse files
committed
Adding reduce() stream operations
1 parent 2b30bf3 commit 7cd3909

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ This repository contains the basic &amp; advance level examples related to Java
3030
* [distinct(), count() and sorted()](Modern-Java-Examples/src/com/learn/streams/StreamsFlatMapExample.java)
3131
* [sort() using Comparator](Modern-Java-Examples/src/com/learn/streams/StreamsComparatorExample.java)
3232
* [filter()](Modern-Java-Examples/src/com/learn/streams/StreamsFilterExample.java)
33+
* [reduct()](Modern-Java-Examples/src/com/learn/streams/StreamsReduceExample.java)
3334

3435

3536

0 commit comments

Comments
 (0)