From 8441d41fdc5e740d4dbd1ce0909586bc42959d47 Mon Sep 17 00:00:00 2001 From: raghav-jha Date: Mon, 26 Mar 2018 01:37:31 +0530 Subject: [PATCH] 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 --- .../java/com/baeldung/array/SumAndAverageInArray.java | 6 +++--- .../com/baeldung/array/SumAndAverageInArrayTest.java | 9 +++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java b/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java index e7d7172fdb..da64c5e9a7 100644 --- a/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java +++ b/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java @@ -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); } } diff --git a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java index 3385ed690f..5597dbd542 100644 --- a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java +++ b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java @@ -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); + } }