How do you get the first element in a collection in JSTL/EL?
12,338
<c:set var="widgetcode" value="${container.widgets[0]}"/>
Author by
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
My
container
contains multiplewidgets
.I'm looping over them and the
widgetcode
variable is set with the value of the lastwidget
in the loop.But what I really want is the first
widget
in the collection.How do I get this without looping?
<c:choose> <c:when test="${fn:length(container.widgets) > 0}"> <c:forEach items="${container.widgets}" var="widgetId" varStatus="status"> <c:set var="widgetcode" value="/widget/<c:out value="${widgetId}"/>"/> </c:forEach> </c:when> <c:otherwise> <c:set var="widgetcode" value="/widget/000"/> </c:otherwise> </c:choose>
-
RustyTheBoyRobot over 10 yearsNote: this only works for indexed collections. Maps and Sets can't use this syntax. stackoverflow.com/q/1000876/557481