Question

I have request attribute "dataSetList" which is a list of object DataSet. I'm displaying its data through JSTL. Everything is fine there.

But I'm just not happy with my JSTL code below because of the two inner forEach statements. fruitList and priceList contain the exact same amount of elements. So I'd to have one forEach that will loop through both of their contents. But I'm not sure how to that in JSTL.

Any ideas?

The DataSet Object

public class DataSet {
    String group;
    List<String> fruitList = new ArrayList<String>();
    List<String> priceList = new ArrayList<String>();
}

For Clarity and Completion

List<DataSet> dataSetList = new ArrayList<DataSet>();
// set all data here
request.setAttribute("dataSetList", dataSetList);

The two inner JSTL forEach that I'd like to make into one

<c:forEach items="${dataSetList}" var="dataSetVar">
    ${dataSetVar.group} <br/>  
    <c:forEach items="${dataSetVar.fruitList}" var="fruit">                 
        ${fruit} 
    </c:forEach>

    <c:forEach items="${dataSetVar.priceList}" var="price">                 
        ${price} 
    </c:forEach>          
</c:forEach>
Was it helpful?

Solution

You can use varStatus attribute to get the index of the current item:

<c:forEach items="${dataSetList}" var="dataSetVar">
    ${dataSetVar.group} <br/>  
    <c:forEach items="${dataSetVar.fruitList}" var="fruit" varStatus="loopCount">                 
        <c:out value="${fruit}" /> 
        <c:out value="${dataSetVar.priceList[loopCount.index]}" />
    </c:forEach>       
</c:forEach>

But note that your version and this one will give different output. With this single loop, each iteration will print elements from both list. While in your code, first all elements from fruitList is printed, and then all elements from priceList is printed. Choose which ever you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top