forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumOfArray.java
More file actions
40 lines (35 loc) · 877 Bytes
/
SumOfArray.java
File metadata and controls
40 lines (35 loc) · 877 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.examplehub.maths;
import java.util.stream.IntStream;
public class SumOfArray {
/**
* Calculate sum of array.
*
* @param numbers the numbers need to be calculated.
* @return the sum of array.
*/
public static int sum(int[] numbers) {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
/**
* Calculate sum of using lambda expression.
*
* @param numbers the numbers need to be calculated.
* @return the sum of array.
*/
public static int sumWithLambda(int[] numbers) {
return IntStream.of(numbers).sum();
}
/**
* Calculate sum of using recursion.
*
* @param numbers the numbers need to be calculated.
* @return the sum of array.
*/
public static int sum(int[] numbers, int len) {
return len == 0 ? 0 : numbers[len - 1] + sum(numbers, len - 1);
}
}