Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freemarker and hashmap. How do I get key-value

I have a hash map as below

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

My Freemarker template is:

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

The goal is to display key-value pair in the HTML that I'm generating. Please help me to do it. Thanks!

like image 685
Damien-Amen Avatar asked Feb 11 '13 21:02

Damien-Amen


People also ask

How will you retrieve key value pair using HashMap?

To get the key and value elements, we should call the getKey() and getValue() methods. The Map. Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.

How do I get the key of a map list?

To retrieve the set of keys from HashMap, use the keyset() method. However, for set of values, use the values() method.


2 Answers

Code:

Map root = new HashMap();
HashMap<String, String> test1 = new HashMap<String, String>();
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

Template:

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

Output:

<body>
    two = 2 
    one = 1 
    three = 3 
</body>
like image 88
ollo Avatar answered Oct 17 '22 09:10

ollo


Since 2.3.25, you can do this:

<body>
<#list hello as key, value> 
    ${key} = ${value} 
</#list> 
</body>
like image 25
ddekany Avatar answered Oct 17 '22 08:10

ddekany