'How to iterate over map using mustache in java

I'm newbie to mustache and was wondering how to iterate over HashMap using mustache given this Map

Map mapA = new HashMap();

mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");

The map key names vary. Ideally, I want mustache to iterate over both its key and values. So in java it will look like this:

for (Map.Entry<String, Object> entry : mapA.entrySet()) {
   String key = entry.getKey();
   String value = entry.getValue();
   // ...
} 

So can someone tell me how to achieve above in mustache. I mean how would the template looks like? I tried this template but had no luck so far :(

{{#mapA}}
  <li>{{key}}</li>
  <li>{{value}}</li>
{{/mapA>

So when I run this template, the output <li> tags comes out empty, why? Thanks.



Solution 1:[1]

it is much simpler than that, just do it like this:

{{#mapA}}
  {{#entrySet}}
    <li>{{key}}</li>
    <li>{{value}}</li>
  {{/entrySet}}
{{/mapA}}

Solution 2:[2]

As @Dici mentioned above, you can use an entrySet. You do not have to use any special options on the factory and can pass it directly to execute. In your template you can use a top level map if your template is very simple.

Java

Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

Writer writer = new OutputStreamWriter(System.out);
MustacheFactory mustacheFactory = new DefaultMustacheFactory();
Mustache template = mustacheFactory.compile("map.template");
template.execute(writer, map.entrySet()).close();

Mustache Template (map.template)

{{#.}}
keylabel:{{key}} : valuelabel:{{value}}
{{/.}}

Result

keylabel:key1 : valuelabel:value1
keylabel:key2 : valuelabel:value2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lutz
Solution 2 milesoldenburg