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

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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