How to Loop Through a Hashmap in Jsp

How to iterate a map in JSP?

When iterating over a map using <c:forEach> you're, in fact, iterating over a collection of entries, these entries have both "key" and "value" fields.

Try the following:

<c:forEach var="entry" items="${map}">
key is ${entry.key}
<c:forEach var="info" items="${entry.value}">
info is ${info}
</c:forEach>
</c:forEach>

How to iterate HashMap using JSTL forEach loop?

Try this,

suppose my MAP is :-

Map<String, String> countryList = new HashMap<String, String>();
countryList.put("United States", "Washington DC");
countryList.put("India", "Delhi");
countryList.put("Germany", "Berlin");
countryList.put("France", "Paris");
countryList.put("Italy", "Rome");

request.setAttribute("capitalList", countryList);

So in JSP ,

<c:forEach var="country" items="${capitalList}">
Country: ${country.key} - Capital: ${country.value}
</c:forEach>

Hope this helps !

Iterating HashMap of HashMap in JSP in a Spring Application

You can use JSTL to iterate over HashMap of HashMap.

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

Try like this:

   <c:forEach var="entry" items="${hm}">
Key: <c:out value="${entry.key}"/>
Value: <c:out value="${entry.value}"/>
<c:set var="hm1" value="${Value}">
<c:forEach var="entry" items="${hm1}"/>
Key1: <c:out value="${entry1.key}"/>
Value1: <c:out value="${entry1.value}"/>
</c:forEach>
</c:forEach>

JSTL loop through multidimensional hashmap

Shouldn't it be items="${items.value}?

Looping through List<HashMap<String,Object>> in JSP

You do it the same way as for any other list, using the JSTL forEach tag:

<c:forEach var="map" items="${contactsList}">
<tr>
<td><c:out value="${map['firstName']}"/>
<td><c:out value="${map['lastName']}"/>
...
</tr>
</c:forEach>

A few notes:

  • scriptlets are obsolete and considered bad practice for more than 10 years. Don't use scriptlets. Use the JSTL and the JSP EL. The code you posted in the question should be inside a controller servlet.
  • Why use a HashMap to store contact information. You should define a Java Bean class named Contact, and return a List<Contact>. Java is an OO language. Define and use objects.


Related Topics



Leave a reply



Submit