Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in velocity can you iterate through a java hashmap's entry set()?

Can you do something like this in a velocity template?

#set ($map = $myobject.getMap() ) #foreach ($mapEntry in $map.entrySet())     <name>$mapEntry.key()</name>     <value>$mapEntry.value()</value> #end 

it outputs blank tags like so:

<name></name>  

and

<value></value>  

What am I doing wrong?

like image 840
Ayrad Avatar asked Jan 12 '10 15:01

Ayrad


People also ask

How do you iterate through a map object?

Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map , in insertion order. The function gets passed the value, key and the Map object on each iteration.

Can we add elements to map while iterating?

No, you can't; if you try this, you will get a ConcurrentModificationException when you use the iterator after modifying the map.


1 Answers

Your mistake is referring to key and value as methods (with trailing "()" parenthesis) instead of as properties. Try this:

#set ($map = $myobject.getMap() ) #foreach ($mapEntry in $map.entrySet())     <name>$mapEntry.key</name>     <value>$mapEntry.value</value> #end 

In other words, use either a property, like mapEntry.key, or the method, like mapEntry.getKey().

like image 109
Yoni Avatar answered Sep 20 '22 15:09

Yoni