2012-04-01 63 views
3

当我在速度模板文件中传递Map<String,String>,并尝试打印地图的值时,它将按照ASCII值进行排序。速度模板文件中如何访问速度模板文件中的地图

我做如下:

这是我的速度模板文件::

#set($tocList=${mapReference.mapValue}) 
#set($tocEntry="") 

<div > 
#foreach($tocEntry in $tocList.keySet()) 
    <a href="#$tocEntry">$tocList.get($tocEntry)</a><br/> 
#end 
</div> 

我的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); 

输出是:

<div> 
    <a href="#dghjdhdf">gI Ml</a><br/> 
    <a href="#chdgfhd">gBc Jk</a><br/> 
    <a href="#sdfhfg">Df lm</a><br/> 
</div> 

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

回答

8

的HasMap的顺序不会随着时间保持恒定,从Javadoc

此类不保证作为对地图的顺序;在 特别是,它不能保证该订单随着时间的推移将保持恒定 。

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

此链接列表定义了迭代顺序,这通常是在哪个键插入到地图中的 顺序

+0

没有[link](http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html) – 2016-12-07 01:41:19