Replace For-Loop with Stream::sum

Properties

Property Value
First seen in jSparrow version 2.2.0
Minimum Java version 8
Remediation cost 10 min

Description

Transforms enhanced for-loops which are only used for summing up the elements of a collection into a stream and uses the sum operation to compute the result.

Benefits

Applying this rule yields no major performance benefits. One could argue that readability is somewhat improved, at least if one is familiar with lambdas.

Requirement & Tags

Requirements

Java 8

Code Changes

List of integers

Pre

List<Integer> numbers = generateIntList(input);
int sum = 0;
for(int n : numbers) {
    sum += n;
}

Post

List<Integer> numbers = generateIntList(input);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();

List of doubles

Pre

List<Double> numbers = generateDoubleList(input);
double sum = 0;
for(double n : numbers) {
    sum += n;
}

Post

List<Double> numbers = generateDoubleList(input);
double sum = numbers.stream().mapToDouble(Double::doubleValue).sum();

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version: