Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse template for wrapping an iterable selection in a for each loop

Tags:

java

eclipse

I want to select an Iterable, press Alt+Shift+Z to get the "Surround With" context menu, and have a foreachwrap template displayed that will wrap the selection in a for each loop with the appropriate format.

For example, i want to select

someObject.getSomeList()

and generate this

for (SomeListType someListType : someObject.getSomeList()) {

}

I've tried something like this, but it doesn't seem to work:

for( ${t:elemType(ls)} ${:name(t)} : ${ls:line_selection} )
{
    ${cursor}
}
like image 588
Kevin Wong Avatar asked Aug 19 '10 16:08

Kevin Wong


1 Answers

Use QuickFix (Ctrl+1 on Win/Lin or Cmd+1 on the Mac).

You can get the desired behavior with the following approach:

  1. Write the statement that returns the iterable collection, e.g.

    someObject.getSomeList()
    
  2. Press Ctrl+1 (Cmd+1 on the Mac) and select Assign statement to a new local variable (there is even a direct combination for this action (Cmd+2 L on the Mac), however, if you want to use it, it probably depends on how much different combinations do you want to remember)

  3. Write no more than

    fore
    

    and press Ctrl+1 (Cmd+1) again, then select Iterate over an array or iterable (simply pressing Enter right after the quickfix menu appears is usually enough at this point) and you get something like this:

    for (Content content : someList) {
    
    }
    

You can now even inline the usage of the local variable to get rid of it again (using QuickFix of course ;). QuickFix is really powerful, I've hardly ever used any templates since that feature was published.

like image 89
Martin Klinke Avatar answered Sep 18 '22 08:09

Martin Klinke