Search code examples
jakarta-eejstl

How to select the first element of a set with JSTL?


I managed to do it with the next code but there must be an easier way.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>


<c:if test="${fn:length(attachments) > 0}">
    <c:forEach var="attachment" items="${attachments}" varStatus="loopCount">
        <c:if test="${loopCount.count eq 1}">
         attachment.id
        </c:if>
    </c:forEach>
</c:if>

Solution

  • You can access individual elements with the array [] operator:

    <c:out value="${attachments[0].id}" />
    

    This will work for arrays and lists. It won't work for maps and sets. In that case you must put the key of the element inside the brackets.