BAEL-1586 Modified logic to use forEach loop (#3879)

* BAEL-1586 Modified logic to use forEach loop

* BAEL-1586 Added Unit Test For Finding Average Given an Empty Array
This commit is contained in:
raghav-jha 2018-03-26 01:37:31 +05:30 committed by pauljervis
parent efa0bcaf85
commit 8441d41fdc
2 changed files with 12 additions and 3 deletions

View File

@ -6,8 +6,8 @@ public class SumAndAverageInArray {
public static int findSumWithoutUsingStream(int[] array) {
int sum = 0;
for (int index = 0; index < array.length; index++) {
sum += array[index];
for (int value : array) {
sum += value;
}
return sum;
}
@ -22,6 +22,6 @@ public class SumAndAverageInArray {
}
public static double findAverageUsingStream(int[] array) {
return Arrays.stream(array).average().getAsDouble();
return Arrays.stream(array).average().orElse(Double.NaN);
}
}

View File

@ -38,4 +38,13 @@ public class SumAndAverageInArrayTest {
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
}
@Test
public void givenAnEmptyIntArray_whenUsingStream_thenFindAverage() {
int[] array = {};
double expectedAvgOfArray = Double.NaN;
double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array);
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.00);
}
}