Approach 1:
1)Take Stream Object on Array then apply sum method directly.
int[] numbers = new int[]{2,1,3,5,6,7,8,9};
int sum1 = Arrays.stream(numbers).sum();
Approach 2:
2)Take Stream Object on array then apply reduce method by passing lambda expression.
int[] numbers = new int[]{2,1,3,5,6,7,8,9};
int sum2 = Arrays.stream(numbers)
.reduce((x,y)>x+y).getAsInt();
Approach 3 :
3) Take Stream Stream object based on array then apply reduce method by passing method referencing in java
int[] numbers = new int[]{2,1,3,5,6,7,8,9};
int sum3 =Arrays.stream(numbers)
.reduce(Integer::sum).getAsInt();
Approach 4:
4) Create IntStream from array then apply sum method.
int[] numbers = new int[]{2,1,3,5,6,7,8,9};
int sum4 =IntStream.of(numbers).sum();
Approach 5:
5) Create Summary Statistics from streams then apply sum method.
int[] numbers = new int[]{2,1,3,5,6,7,8,9};
IntSummaryStatistics intSummaryStatistics = Arrays.stream(numbers).summaryStatistics();
Long sum5 = intSummaryStatistics.getSum();
Here is the full tutorial:
Leave a Reply