简体   繁体   English

如何在速度模板文件中访问地图

[英]How to access map in velocity template file

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). 当我在速度模板文件中传递Map<String,String>时,当尝试打印map的值时,它会被排序(基于ASCII值)。

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 : 我的Java代码是:

 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. 我想按原样打印地图。

The order of the HasMap will not remain constant over time, from Javadoc : Javadoc开始,HasMap的顺序将不会保持不变:

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: 要保留订单,您可以考虑使用LinkedHashMap ,如下所示:

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map 此链接列表定义迭代排序,通常是键插入映射的顺序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM