# Replace For-Loop with Stream::sum

# 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.

# Tags

# 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();

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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