当我通过一个Map<String,String>in velocity模板文件时,当试图打印map的值时,它会被排序(基于ASCII值).
我这样做:
这是我的速度模板文件::
#set($tocList=${mapReference.mapValue})
#set($tocEntry="")
<div >
#foreach($tocEntry in $tocList.keySet())
<a href="#$tocEntry">$tocList.get($tocEntry)</a><br/>
#end
</div>
Run Code Online (Sandbox Code Playgroud)
我的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);
Run Code Online (Sandbox Code Playgroud)
输出是:
<div>
<a href="#dghjdhdf">gI Ml</a><br/>
<a href="#chdgfhd">gBc Jk</a><br/>
<a href="#sdfhfg">Df lm</a><br/>
</div>
Run Code Online (Sandbox Code Playgroud)
为什么这些值会被排序?我想按原样打印地图.
从Javadoc开始,HasMap的顺序将不会保持不变:
这个类不保证地图的顺序; 特别是,它不保证订单会随着时间的推移保持不变.
要保留订单,您可以考虑使用LinkedHashMap,如下所示:
此链接列表定义迭代排序,通常是键插入映射的顺序
| 归档时间: |
|
| 查看次数: |
17012 次 |
| 最近记录: |