1. Overview
In this article, we will see how to add all the elements of an array. For example we will use int[] array.
2. Content
Let say for example we have int[] arr = { 4, 67, 3, 4, 2 }. Below code adds all the values and returns the sum.
int[] arr = { 4, 67, 3, 4, 2 }; for (int i : arr) { sum = sum + i; } return sum;
The way we add elements is we define a mutable variable called sum and initialize it to zero i.e. 0. Then we iterate over array and pull each element out of array and add it to previous sum. Once the iteration is completed we return the sum.
This method works just fine but there are few issues with it that I would like to discuss:
- Mutability
- By mutability I mean that we initialize the sum variable to 0 and then keep it adding with next element and new sum is copied to sum variable and repeat till the array ends.
- Pull Mechanism
- Pull mechanism refers to pull data out of array. This is called external iteration where a client is responsible to remove data out of container and work with it.
- Parallelism
- The problem with this is that if we have millions of elements in an array, a very good candidate to add values would be to use parallelism. But the for loop seriously limits our abilities to do that.
What is the solution to this? Java 8 introduced primitive stream capabilities that can do several aggregate operations in sequential and parallel.
Let us take a look at it on how to add elements using this new capability.
int[] arr = { 4, 67, 3, 4, 2 }; int sum = IntStream.of(arr).sum(); return sum;
And that’s it. Done. As compared to traditional for loops this capability provides:
- No Mutability
- There are no variables needed to generate the sum. No mutability.
- Internal Iteration
- IntStream class iterates the array internally i.e. it is framework controlled and not client controlled.
- Parallelism Ready Code
- This code may look simple but it it can run is parallel too if we use right API. Parallelism is not always the answer to get results faster. We must be careful while using parallel stream and make sure to add tests and measure performance.
That’s all on adding elements in an array.
Likewise for long[] and double[] we can use LongStream and DoubleStream to add the elements of an array respectively.