13

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}
}
Kevin Wong
  • 13,690
  • 11
  • 40
  • 49
  • 6
    I'm gonna check that out. Alternatively, you can type "foreach", hit Ctrl-Space, and select the "foreach - iterate over an array or Iterable" proposal, and it will generate code from the "foreach" template, using the last-referenced Iterable or array variable. – Ladlestein Aug 19 '10 at 18:01
  • I suggest that you post this under http://stackoverflow.com/questions/1028858/useful-eclipse-java-code-templates to avoid duplication. As for the question, I am kind of dubious. The generic type information is not retained in the bytecode, lack of which would hinder the solution. I am really curious to see the answers! – questzen Aug 20 '10 at 06:11
  • @questzen The generic type information (at least for classes and method signatures) IS retained in the bytecode, or else the Java compiler could not use it. The generic information is not used at runtime, though. – Christian Semrau Feb 26 '11 at 12:08
  • I agree with Ladlestein. This template is already there in eclipse and if you want to use collection other than the latest then just write your statement first i.e. someObject.getSomeList() and then use foreach template by typing "foreach" and press Ctrl+Space. – Amit Mar 08 '11 at 04:54

1 Answers1

5

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.

Martin Klinke
  • 7,070
  • 5
  • 38
  • 62