C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Lambda: To specify the accumulator we use a lambda expression. The ints a and b are added together.
LambdaJava program that uses array, IntStream and reduce
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);
}
}
Output
6
Java program that uses Integer sum method
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);
}
}
Output
6
Java program that uses for-loop, int
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);
}
}
Output
6
Version 1: The sum1 method sums with stream() and reduce. It uses only three lines of code.
Version 2: Sum2 sums with a for-loop and a local variable. It uses five lines of code.
Result: The sum1 method, despite having shorter code, is far slower. It requires about 100x the time of sum2.
Java program that benchmarks sum methods
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);
}
}
Output
524 ms, stream, reduce
4 ms, for-loop
Parallel: With functional constructs, we can place large computations on multiple threads. At some point this would become faster.
Quote: Reduction operations parallelize more gracefully, without needing additional synchronization and with greatly reduced risk of data races (Java Documentation).