Skip to content

Commit 2846836

Browse files
committed
feat(maths): add stream-based averageStream method and validations
1 parent 6d3da37 commit 2846836

1 file changed

Lines changed: 27 additions & 4 deletions

File tree

src/main/java/com/thealgorithms/maths/Average.java

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.thealgorithms.maths;
22

3+
import java.util.Arrays;
4+
import java.util.OptionalDouble;
5+
36
/**
47
* A utility class for computing the average of numeric arrays.
58
*
@@ -13,7 +16,8 @@ public final class Average {
1316

1417
// Prevent instantiation of this utility class
1518
private Average() {
16-
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated.");
19+
throw new UnsupportedOperationException(
20+
"This is a utility class and cannot be instantiated.");
1721
}
1822

1923
/**
@@ -28,7 +32,8 @@ private Average() {
2832
*/
2933
public static double average(double[] numbers) {
3034
if (numbers == null || numbers.length == 0) {
31-
throw new IllegalArgumentException("Numbers array cannot be empty or null");
35+
throw new IllegalArgumentException(
36+
"Numbers array cannot be empty or null");
3237
}
3338
double sum = 0;
3439
for (double number : numbers) {
@@ -49,12 +54,30 @@ public static double average(double[] numbers) {
4954
*/
5055
public static long average(int[] numbers) {
5156
if (numbers == null || numbers.length == 0) {
52-
throw new IllegalArgumentException("Numbers array cannot be empty or null");
57+
throw new IllegalArgumentException(
58+
"Numbers array cannot be empty or null");
5359
}
5460
long sum = 0;
5561
for (int number : numbers) {
5662
sum += number;
5763
}
5864
return sum / numbers.length;
5965
}
60-
}
66+
67+
/**
68+
* Computes the arithmetic mean of a {@code double} array using Java Streams.
69+
*
70+
* <p>This method is a declarative alternative to {@link #average(double[])}.
71+
* Instead of throwing on empty input, it returns an empty {@link OptionalDouble},
72+
* following the convention of the Stream API.
73+
*
74+
* @param numbers an array of {@code double} values, may be {@code null} or empty
75+
* @return an {@link OptionalDouble} with the mean, or empty if input is null/empty
76+
*/
77+
public static OptionalDouble averageStream(double[] numbers) {
78+
if (numbers == null || numbers.length == 0) {
79+
return OptionalDouble.empty();
80+
}
81+
return Arrays.stream(numbers).average();
82+
}
83+
}

0 commit comments

Comments
 (0)