JSTL forEach Iterate Map Example

JSTL forEach loop provides capability to iterate over collection of objects like list or map.

JSTL forEach Iterate Map Example:

Assume that the code below iterates over the Map of 3 products that contains following key-value pair in order, where Sku is key and it is unique number. Value is the name of the pen:

RP01 - Red Pen, GP01 - Green Pen, PP01 - Pink Pen

You want to print the names with its sku.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL forEach varStatus index Example</title>
  <c:forEach items="${productMap}" var="entry" varStatus="status">
     <c:out value="${entry.key}"/> -- <c:out value="${entry.value}" escapeXml="false" />


RP01 -- Red Pen

GP01 -- Green Pen

PP01 -- Pink Pen

As you can see above, we printed name of the products with its sku in the Map. While iterating, we defined each element as an entry defined in variable var. By invoking key method, we get key of the entry. Same way we got value of the entry by invoking value method.