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

JavaXmlVelocityTemplate Engine

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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().

Solution 2 - Java

I'm looking for a way to loop through a HashMap in velocity, and this will work too.

#set ($map = $myobject.getMap())
#foreach( $key in $map.keySet())
      <name>$key</name>
      <value>$resume.get($key)</value>
#end

Just like the way you would loop through a HashMap in java.

Solution 3 - Java

To clarify (I cannot comment), in general you can use either the Java get methods, or replace them by the corresponding name without with a small letter and without ().

So $mapEntry.getKey() or map.key.

Solution 4 - Java

Here the Value

itemsValue={data1=1,data2=2,data3=3}

So , we need to iterate the group of value;

foreach ($key in ${itemsValue.keySet()})
   if($itemsValue.get($key)==1)
        Condition
   end
end

In the above code we can see check the value will be like -"data1,data2 etc ..." but after using the get(), we can able to get the instance value.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAyradView Question on Stackoverflow
Solution 1 - JavaYoniView Answer on Stackoverflow
Solution 2 - JavaAllan RuinView Answer on Stackoverflow
Solution 3 - JavaVincent GerrisView Answer on Stackoverflow
Solution 4 - Javauser7490061View Answer on Stackoverflow