Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor foreach to for loop

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)

like image 426
Thomas Weller Avatar asked Jun 05 '15 08:06

Thomas Weller


People also ask

Can foreach be used in a variable?

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.


3 Answers

Mouseover the for statement, right-click, Quick fix (Ctrl+1), convert to indexed loop.

Should work!

like image 50
Massimo Avatar answered Oct 14 '22 13:10

Massimo


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);
}
like image 20
JB Nizet Avatar answered Oct 14 '22 13:10

JB Nizet


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

Screenshot of quick fix options

like image 39
Marvin Avatar answered Oct 14 '22 14:10

Marvin