How To Iterate HashMap in FreeMarker (FTL)

In this short article we will see how to iterate an HashMap in FreeMarker template. Consider below code which is normally used to iterate a List in FTL.

// Java List<String> cityList = new ArrayList<String>(); cityList.add("Washington DC"); cityList.add("Delhi"); cityList.add("Berlin"); cityList.add("Paris"); cityList.add("Rome"); request.setAttribute("cityList", cityList); // FTL template <#list cityList as city> <b> ${city} </b> </#list>
Code language: Java (java)

Output:

Washington DC Delhi Berlin Paris Rome

Here in above code, we created a List object and passed it to FTL page. In FTL we used <#list> to iterate and print its values.

Problem Statement

So here’s the problem statement. I have an Hashmap which I want to iterate and display in my FTL (FreeMarker) template. Consider following code in Java.
So how to iterate this Hashmap in FTL and display its values?

//Java Map<String, String> countryCapitalList = new HashMap<String, String>(); countryCapitalList.put("United States", "Washington DC"); countryCapitalList.put("India", "Delhi"); countryCapitalList.put("Germany", "Berlin"); countryCapitalList.put("France", "Paris"); countryCapitalList.put("Italy", "Rome"); request.setAttribute("capitalList", countryCapitalList);
Code language: Java (java)

Solution

Well, the above hashmap can be iterated in FTL using following code:

<#list capitalList?keys as key> ${key} = ${capitalList[key]} </#list>
Code language: Java (java)

Output:

United States = Washington DC India = Delhi Germany = Berlin France = Paris Italy = Rome

In above code, we used ?keys attribute to get the keySet of HashMap. This key set is iterated and corresponding value is fetched by user.get(key) method.
Note: One thing that’s worth noting here is that the sequence in which the values are printing may be different then the actual sequence in which values are added in hashmap. This is because, hashmap doesn’t preserve order or values. If you want to preserve the sequence of keys use LinkedHashMap.

Hope this helps.

View Comments

  • How do i access the next element in a sequence in freemarker
    [code language="xml"]
    <#assign elements = [1,2,3,4]
    <#list elements as element>
    ${elements[element_index + 1]}
    </#list>
    [/code]
    I have tried this but doesnt work

  • How do I iterate over a hashmap<String,List> in freemarker? abc() takes as input only strings or arrays. Not lists & the hashmap which I am looking at contains Keys as String & Value as a list of strings.
    I want the output to be like :

    A= apple,mango,banana
    B = x,e,t,

    My code:

    abc().setTargeting('${key?js_string}','${key_value_list_map[key]}');

  • Nice Article. But when I try this:

    ${key} = ${criteriaMap[key]}

    It throws exception:
    freemarker.core.InvalidReferenceException: Expression criteriaMap[key] is undefined.

    However, If i print key only using ${key} , the code works. I dont know why "criteriaMap[key]" is causing trouble.

    Thanks in advance

    PS: There is a Line in your article "corresponding value is fetched by user.get(key) method."
    where is user in the article, its confusing.

    • My last comment was mangled... so again, staring from FreeMarker 2.3.25 you can do this:

      ${key} = ${value}

  • Hi, I'm unable to get the desired output and getting following error:
    FreeMarker template error:
    The following has evaluated to null or missing:
    ==> key [in template "template/xyz.ftl" at line 35, column 19]

    • Code Snippet:

      FROM HERE
      [#if sourceList?? && sourceList?has_content]
      Source: ${sourceList}

      List:

      ${key} = ${value};

      [#else]
      sourceList is empty
      [/#if]
      TILL HERE

      Output (after commenting out [#-- ${key} = ${value}; --])
      FROM HERE

      Source: {a12=Test}
      List:

      TILL HERE
      Would appreciate all the help.

  • when I iterate , I am getting unnecessary key and values like,size, clone, equals etc.. how to avoid those values.

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago