Question

For performance reasons (to reduce object allocation resulting from a bazillion calls to ArrayList.iterator()), I would like to replace all foreach loops with for loops, in my java project.

Replace:

List<SomeClass> items = createItems();
for (SomeClass item : items) {
    // do something with item
}

With:

SomeClass[] items = createItems();
for (int i = 0; i < items.length; i++) {
    SomeClass item = items[i];
    // do something with item
}

Is there a way to find all occurrences of foreach loops in a project?

Was it helpful?

Solution 2

I have to admit that I do not know IntelliJ much, but the following will work in Eclipse, and I assume that IntelliJ would have a similar feature.

The for each loop was introduced in Java 1.5, so one way to find all those loops would be to set the source level to e.g. 1.4. Then all those foreach loops (and other new language features) will provoke errors.

In Eclipse, go to Preferences (or the project's Properties), Java Compiler, and set the Compiler Compliance Level to 1.4. Then, in the Problems View, you can sort the errors by their Description so all the "for each statement not available" errors line up nicely for you to find.

Again, my solution is for Eclipse, but I'm sure there is something similar in IntelliJ, too.

OTHER TIPS

You can use structural search / replace (from menu Edit - > Find -> Structural ..., it's a built in plugin called "Structural search"):

Search template:

List<$TYPE$> $listVar$ = $init$;
for ($TYPE$ $var$ : $listVar$) {
    $BLOCK$;    
}

Replace template:

$TYPE$[] $listVar$ = $init$;
for (int i = 0; i < $listVar$.length; i++) {
    $TYPE$ $var$ = $listVar$[i];
    $BLOCK$;
}

You need to set unlimited number for $BLOCK$ variable to correctly process whole for block, or even fiddle little bit with regexp to catch lines that don't end with ;.

Note that this won't change return type of createItems() method ($init$ in the template). But you are left with bunch of compile time errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top