An array contains numbers (such as ints). In Java, methods can be used to sum these. A for
-loop can instead be used. The approaches have different advantages.
With reduce, a method from the IntStream
class
, we apply a method to all elements. With an accumulator, we sum the numbers. This approach is more complex than the for
-loop.
We first convert our int
array into an IntStream
with Arrays.stream
. We then call reduce—the first should be left as 0. The second is the accumulator method.
import java.util.Arrays; import java.util.stream.IntStream; public class Program { public static void main(String[] args) { // This is an array. int[] array = { 1, 2, 3 }; // Convert array to a stream. IntStream s = Arrays.stream(array); // Use reduce to sum all elements in the array. int sum = s.reduce(0, (a, b) -> a + b); // Display our result. System.out.println(sum); } }6
We do not need to directly specify the lambda. We can use the Integer::sum
method provided in Java. This does the same thing as the previous example.
import java.util.Arrays; import java.util.stream.IntStream; public class Program { public static void main(String[] args) { int[] array = { 1, 2, 3 }; IntStream s = Arrays.stream(array); // Use Integer sum method. int sum = s.reduce(0, Integer::sum); System.out.println(sum); } }6
For
-loop sumThis program uses a for
-loop to sum all the ints in the array. A for
-each loop, with no index, could instead be used.
public class Program { public static void main(String[] args) { int[] array = { 1, 2, 3 }; int sum = 0; // Use a for-loop to sum the elements. for (int i = 0; i < array.length; i++) { sum += array[i]; } System.out.println(sum); } }6
You can probably guess which version of summing integers is faster. The for
-loop is far faster on small arrays. Here I test this.
stream()
and reduce. It uses only three lines of code.for
-loop and a local variable. It uses five lines of code.import java.util.Arrays; import java.util.stream.IntStream; public class Program { static int sum1(int[] array) { // Uses reduce method. IntStream s = Arrays.stream(array); int sum = s.reduce(0, Integer::sum); return sum; } static int sum2(int[] array) { // Uses for-loop. int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum; } public static void main(String[] args) { int[] array = { 10, 20, 30, 40, 50, 60, 70, 80, 90 }; long t1 = System.currentTimeMillis(); // Version 1: use reduce method. for (int i = 0; i < 10000000; i++) { sum1(array); } long t2 = System.currentTimeMillis(); // Version 2: use for-loop. for (int i = 0; i < 10000000; i++) { sum2(array); } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } }524 ms, stream, reduce 4 ms, for-loop
We saw ways to sum an array of integers. With reduce()
we can sum ints in a stream. With a for
-loop we sum numbers in an imperative way.