How do you get the first element in a collection in JSTL/EL?

12,338
<c:set var="widgetcode" value="${container.widgets[0]}"/>
Share:
12,338
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    My container contains multiple widgets.

    I'm looping over them and the widgetcode variable is set with the value of the last widget 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
    RustyTheBoyRobot over 10 years
    Note: this only works for indexed collections. Maps and Sets can't use this syntax. stackoverflow.com/q/1000876/557481