JSTL forEach continue Example

JSTL forEach loop provides capability to iterate over collection of objects like list or map. Sometimes it is required to skip the current iteration and continur to the next iteration or completly break the iteration. In JAVA loops ( for loop or while loop), this can be achieved using continue or break statements.  

JSTL forEach loop does not provide built in capability like continue or break statement. The solution to this is to use if statement within forEach loop such that the code within forEach block does not execute when certain conditions are met.

JSTL forEach continue Example:

Assume that the code below iterates over the list of 3 products that contains following names in order:

Red Pen, Green Pen, Pink Pen

You want to print the names except the name of the product at index 1. ( some condition to skip current iteration )

<!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="${productList}" var="product" varStatus="status">
     <c:if test="${status.index != 1}">
     <c:out value="${status.index}"/>.<c:out value="${product.name}" escapeXml="false" />


0. Red Pen

2. Pink Pen

As you can see above, we printed name of the products with its index in the list. We wanted to skip iteration when index is 1. In JAVA, we could have done it very easily with continue statement. Since we do not have continue statement in JSTL, we used JSTL IF tag in such a way that it executes only when index is other than 1.

This is exactly not continue statement but end result is same and I believe that is what a programmer needs when certain built in functionalities are not available.