2012-04-01 26 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