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 da64c5e9a7..49df5ba986 100644 --- a/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java +++ b/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java @@ -16,6 +16,10 @@ public class SumAndAverageInArray { return Arrays.stream(array).sum(); } + public static int findSumUsingStream(Integer[] array) { + return Arrays.stream(array).mapToInt(Integer::intValue).sum(); + } + public static double findAverageWithoutUsingStream(int[] array) { int sum = findSumWithoutUsingStream(array); return (double) sum / array.length; 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 5597dbd542..208075cb57 100644 --- a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java +++ b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java @@ -21,6 +21,15 @@ public class SumAndAverageInArrayTest { Assert.assertEquals(expectedSumOfArray, actualSumOfArray); } + @Test + public void givenAnBoxedIntegerArray_whenUsingStream_thenFindSum() { + Integer[] array = new Integer[]{1, 3, 4, 8, 19, 20}; + int expectedSumOfArray = 55; + int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array); + + Assert.assertEquals(expectedSumOfArray, actualSumOfArray); + } + @Test public void givenAnIntArray_whenNotUsingStream_thenFindAverage() { int[] array = { 1, 3, 4, 8, 19, 20 };