How to access map in velocity template file
17,872
The order of the HasMap will not remain constant over time, from Javadoc:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
To remain the order, you can consider use LinkedHashMap as following suggested:
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map
Comments
-
ved almost 2 years
when I passed a
Map<String,String>
in velocity template file, and when try to print the values of map it get sorted (on the basis of ASCII values).I am doing as follows:
this is my velocity template file::
#set($tocList=${mapReference.mapValue}) #set($tocEntry="") <div > #foreach($tocEntry in $tocList.keySet()) <a href="#$tocEntry">$tocList.get($tocEntry)</a><br/> #end </div>
My Java code is :
Map<String, String> map=new HashMap<String, String>(); Map<String,HashMap> m1=new HashMap<String, HashMap>(); \\values that we want to print in template file map.put("sdfhfg", "Df lm"); map.put("chdgfhd", "gBc Jk"); map.put("dghjdhdf", "gI Ml"); m1.put("mapValue", (HashMap) map); VelocityEngine velocityEngine = VelocityEngineFactory.getVelocityEngine(); VelocityContext context = new VelocityContext(); context.put("img",model); context.put("mapReference",m1); context.put("iterator", new IteratorTool()); Template t = velocityEngine.getTemplate("tocTemplate.vm"); StringWriter writer = new StringWriter(); t.merge(context , writer); System.out.println(writer);
Output is:
<div> <a href="#dghjdhdf">gI Ml</a><br/> <a href="#chdgfhd">gBc Jk</a><br/> <a href="#sdfhfg">Df lm</a><br/> </div>
Why these values get sorted? I want to print map as it is.
-
man.2067067 over 7 yearsdoesn't the link