2013-02-11 40 views
13

मैं एक हैश मानचित्र के नीचे के रूप में है मिलता हैफ्रीमार्कर और हैशपैप। मैं कैसे कुंजी-मान

HashMap<String, String> map = new HashMap<String, String>(); 
map.put("one", "1"); 
map.put("two", "2"); 
map.put("three", "3"); 

Map root = new HashMap(); 
root.put("hello", map); 

मेरे Freemarker टेम्पलेट है:

<html><body> 
    <#list hello?keys as key> 
     ${key} = ${hello[key]} 
    </#list> 
</body></html> 

लक्ष्य एचटीएमएल कि मैं में कुंजी-मान पेयर प्रदर्शित करने के लिए है मी उत्पन्न करना कृपया इसे करने में मेरी मदद करें। धन्यवाद!

+1

क्या प्रदर्शित किया गया है? त्रुटि कहां है? – Aubin

उत्तर

33

कोड:

HashMap<String, String> test1 = new HashMap<String, String>(); 
Map root = new HashMap(); 
test1.put("one", "1"); 
test1.put("two", "2"); 
test1.put("three", "3"); 
root.put("hello", test1); 


Configuration cfg = new Configuration(); // Create configuration 
Template template = cfg.getTemplate("test.ftl"); // Filename of your template 

StringWriter sw = new StringWriter(); // So you can use the output as String 
template.process(root, sw); // process the template to output 

System.out.println(sw); // eg. output your result 

टेम्पलेट:

<body> 
<#list hello?keys as key> 
    ${key} = ${hello[key]} 
</#list> 
</body> 

आउटपुट:

<body> 
    two = 2 
    one = 1 
    three = 3 
</body> 
+3

2.3.25 के बाद से एक बेहतर तरीका है; देखें: https://stackoverflow.com/a/38273478/606679 – ddekany

3

एक ऐसा नक्शा बरकरार रखता है का उपयोग करें कुंजी-मान जोड़ों की प्रविष्टि आदेश: LinkedHashMap

+0

यह उत्तर यह मान रहा है कि समस्या यह है कि आउटपुट प्रविष्टि क्रम में नहीं है। मुझे यकीन नहीं है कि यह सच है या नहीं। – Gray

11

2.3.25 के बाद से, आप यह कर सकते हैं:

<body> 
<#list hello as key, value> 
    ${key} = ${value} 
</#list> 
</body> 
0

2.3.25 से पहले, वस्तुओं से युक्त कुंजी के मामले में, आप

उपयोग करने के लिए कोशिश कर सकते हैं
<#assign key_list = map?keys/> 
<#assign value_list = map?values/> 
<#list key_list as key> 
    ... 
    <#assign seq_index = key_list?seq_index_of(key) /> 
    <#assign key_value = value_list[seq_index]/> 
    ... 
    //Use the ${key_value} 
    ... 
</#list>