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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9964075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:05:13  来源:igfitidea点击:

How to access map in velocity template file

javavelocity

提问by ved

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>in 速度模板文件,并尝试打印地图的值时,它会被排序(基于 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.

为什么这些值被排序?我想按原样打印地图。

回答by Pau Kiat Wee

The order of the HasMap will not remain constant over time, from Javadoc:

HasMap 的顺序不会随着时间的推移保持不变,来自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 LinkedHashMapas following suggested:

为了保持顺序,您可以考虑使用LinkedHashMap如下建议:

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map

这个链表定义了迭代顺序,通常是将键插入到映射中的顺序