18

We can iterate through collection easily by pressing Ctrl+Alt+T,

And then I wanted to create such template for iterating through map: I wrote these lines to template text box:

for (Map.Entry<$ELEMENT_TYPE$> $VAR$ : $SELECTION$.entrySet()) {
  $END$
}

Now it is generating these codes:

 HashMap<String,Object> map=new HashMap<String,Object>();
    for (Map.Entry<Object> objectEntry : map.entrySet()) {

    }

Map.Entry<Object> should be Map.Entry<String,Object>. I cannot find a way to introduce variable correctly. How can I do that?

Bas Leijdekkers
  • 23,709
  • 4
  • 70
  • 68
Jama A.
  • 15,680
  • 10
  • 55
  • 88
  • 1
    I use `iter` + `` and select `map.entrySet()` Do you need to create a new template to do this? If so you can look at how this one is implemented already. – Peter Lawrey Oct 01 '12 at 08:53

3 Answers3

46

It is easier if you just type iter and then Tab.

You will get a drop-down and there you can choose map.entrySet() and it will give you:

for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {

}
maba
  • 47,113
  • 10
  • 108
  • 118
2

To view a list of live template available: Ctrl + J and then Tab.

From there you will have list of live template, iter (for each loop) will be on the list.

Sivabalan
  • 2,908
  • 2
  • 24
  • 21
0

I wrote this, it works in 1 step. I also like having the key and value in there already, but those can be omitted:

for (Map.Entry<$KEY_TYPE$, $VALUE_TYPE$> $PAIR$ : $ITERABLE_TYPE$.entrySet()) {
    $KEY_TYPE$ key = $PAIR$.getKey();
    $VALUE_TYPE$ value = $PAIR$.getValue();
    $END$
}

Variables:

  • KEY_TYPE: guessElementType(iterableVariable())
  • VALUE_TYPE: regularExpression(typeOfVariable(ITERABLE_TYPE),"^.*,(.*)>$", "$1")
  • PAIR: suggestVariableName()
  • ITERABLE_TYPE: variableOfType("java.util.Map")

The large amount of variables and functions make the Live Templates a powerful tool. In VALUE_TYPE, I am using a regular expression to get the ValueType out of Map<KeyType, ValueType>. I tried a lot of "cleaner" approaches, but none worked.