I have a foreach loop in Java (simplified version here)
List<String> names = getNames();
for(String name:names) {
doSomething(name);
}
Is there an automated way to refactor this to a traditional for loop?
I know how to do it manually
List<String> names = getNames();
for(int i=0; i<names.size(); i++) {
String name = names.get(i);
doSomething(name);
}
As you can see, there is a bit of typing needed in the for statement itself as well as introducing the variable name again and assign it the value names.get(i). In total, the manual edit is too error-prone for me.
Why do I want to do this? I have to fix a bug and the fix is to start at index 1 instead of index 0 and end at index n-1 instead of the end (unfortunately I can't fix the input right away, I need to wait for a library update if that's recognized as a bug).
What have I tried? I right-clicked on the for keyword and clicked on "Refactor", but as far as I can get from the context menu entries, nothing in there would do the work for me.
Why do I think this could theoretically work? Because similar functionality exists in Resharper for Visual Studio (C#).
FYI: I'm using Eclipse Luna SR 2 (4.4.2)
The variable var is local to the foreach loop; if a variable outside the loop has the same name, it is unaffected by the foreach loop. In fact, var is optional; if you don't specify a variable in the foreach statement, the special variable $_ can be used inside the loop to represent the values in list.
Mouseover the for statement, right-click, Quick fix (Ctrl+1), convert to indexed loop.
Should work!
List<String> names = getNames();
names = names.subList(1, names.size() - 1);
for(String name : names) {
doSomething(name);
}
Of course, you could put that into a reusable method if you need to do it several times:
public static List<String> fixList(List<String> names) {
return names.subList(1, names.size() - 1);
}
and then use it as
List<String> names = fixList(getNames());
for(String name : names) {
doSomething(name);
}
In my eclipse (Kepler RC2) it works to select the for keyword and either use the quick fix from the context menu or hit CTRL+1 for the shortcut. Eclipse then offers me "Convert to indexed 'for' loop" or "Convert to Iterator-based 'for' loop".

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With