154

How can I loop through a HashMap in JSP?

<%
    HashMap<String, String> countries = MainUtils.getCountries(l);
%>

<select name="country">
    <% 
        // Here I need to loop through countries.
    %>
</select>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
blub
  • 1,541
  • 2
  • 10
  • 3
  • 18
    By the way, a `HashMap` is by nature unordered. Are you certain you don't need `TreeMap` (automagic sort by key) or `LinkedHashMap` (maintains insertion order)? – BalusC Dec 02 '09 at 21:27

3 Answers3

324

Just the same way as you would do in normal Java code.

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

However, scriptlets (raw Java code in JSP files, those <% %> things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib and declare the needed taglibs in top of JSP). It has a <c:forEach> tag which can iterate over among others Maps. Every iteration will give you a Map.Entry back which in turn has getKey() and getValue() methods.

Here's a basic example:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach items="${map}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>

Thus your particular issue can be solved as follows:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<select name="country">
    <c:forEach items="${countries}" var="country">
        <option value="${country.key}">${country.value}</option>
    </c:forEach>
</select>

You need a Servlet or a ServletContextListener to place the ${countries} in the desired scope. If this list is supposed to be request-based, then use the Servlet's doGet():

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    Map<String, String> countries = MainUtils.getCountries();
    request.setAttribute("countries", countries);
    request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}

Or if this list is supposed to be an application-wide constant, then use ServletContextListener's contextInitialized() so that it will be loaded only once and kept in memory:

public void contextInitialized(ServletContextEvent event) {
    Map<String, String> countries = MainUtils.getCountries();
    event.getServletContext().setAttribute("countries", countries);
}

In both cases the countries will be available in EL by ${countries}.

See also:

starball
  • 20,030
  • 7
  • 43
  • 238
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 2
    @Khue: yes, you can also put attributes in the session. I only don't see why you would like to duplicate application wide data over multiple sessions. – BalusC Oct 26 '11 at 11:25
  • I think in case of session-based info. Thanks for the very nice explanation. – Khue Vu Oct 27 '11 at 03:56
  • I'm sure the answer is obvious but - why are scriptlets considered poor practice? In the absence of JSTL due to maintaining a legacy application, this is my only option. – Zibbobz May 25 '18 at 18:32
  • @Zibbobz: the text "poor practice" is a link. Click on it. – BalusC May 25 '18 at 18:34
2

Depending on what you want to accomplish within the loop, iterate over one of these instead:

  • countries.keySet()
  • countries.entrySet()
  • countries.values()
Kenny Linsky
  • 1,726
  • 3
  • 17
  • 41
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

Below code works for me

first I defined the partnerTypesMap like below in the server side,

Map<String, String> partnerTypes = new HashMap<>();

after adding values to it I added the object to model,

model.addAttribute("partnerTypesMap", partnerTypes);

When rendering the page I use below foreach to print them one by one.

<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
      <form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>
tk_
  • 16,415
  • 8
  • 80
  • 90