JSTL forEach Map Iteration

JSTL forEach Map Iteration Example explains how to iterating a map using JSTL Taglib

Map is an object that stores key / value pairs. You can find its value from a particular key. Keys must be unique, but values may be duplicated 

Consider a JSP page, which contains a HashMap with lot of key value pairs inside it and we need to iterate and display the values inside that particular HashMap

You can access ${entry.key} and ${entry.value} from a Map using a variable var="entry"

This JSTL 'c:forEach is available for all the List / Collection implementations in java

Following example shows How to iterate a JSTL HashMap using JSTL c:forEach

Note

Please check the table, You can iterate following table items using c:forEach tag

JSTL foreach Collections

Note

You can see List Iteration here JSTL forEach List Iteration

Required Libraries

You need to download

  1. Tomcat 9
  2. JSTL 1.2

Following jar must be in classpath

  1. jstl-1.2.jar

Project Structure

JSTL forEach Map Iteration

JSTL forEach HashMap Iteration

// Iterate HashMap With JSTL
    

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="java.util.HashMap"%>
<%
    HashMap<String,String> numMap = new HashMap<String,String>();
    numMap.put("1","one");
    numMap.put("2","two");
    numMap.put("3","three");
    request.setAttribute("numMap", numMap);
%>
<html>
<body>
    <c:forEach items="${numMap}" var="entry">
        ${entry.key})${entry.value}<br/>
    </c:forEach>
</body>
</html>
Output
1) one
2) two
3) three








Your email address will not be published. Required fields are marked *