Calculate total sum of all numbers in c:forEach loop

Dónal picture Dónal · Sep 19, 2008 · Viewed 54.5k times · Source

I have a Java bean like this:

class Person {
  int age;
  String name;
}

I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages.

The code to generate the table rows will look something like this:

<c:forEach var="person" items="${personList}">
  <tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>

However, I'm struggling to find a way to calculate the age total that will be shown in the final row without resorting to scriptlet code, any suggestions?

Answer

Jon-Erik picture Jon-Erik · Sep 19, 2008

Note: I tried combining answers to make a comprehensive list. I mentioned names where appropriate to give credit where it is due.