# Replace While-Loop with Enhanced For-Loop
# Description
Applying this rule replaces While-loops over iterators with an equivalent for-loop.
# Benefits
Applying this rule leads to more simplicity in the code base by using new language constructs.
# Tags
# Code Changes
Pre
public String testWhileToFor(String input) {
List<String> l = generateList(input);
StringBuilder sb = new StringBuilder();
Iterator<String> iterator = l.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
sb.append(s);
}
return sb.toString();
}
Post
public String testWhileToFor(String input) {
List<String> l = generateList(input);
StringBuilder sb = new StringBuilder();
for (String s : l) {
sb.append(s);
}
return sb.toString();
}
# Limitations
Loops where the body modifies the iterator in some way will not be transformed.
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.
# Properties
Property | Value |
---|---|
Rule ID | WhileToForEach |
First seen in jSparrow version | 1.0.0 |
Minimum Java version | 5 |
Remediation cost | 5 min |