Check a collection size with JSTL
How can I check the size of a collection with JSTL?
Something like:
<c:if test="${companies.size() > 0}">
</c:if>
<c:if test="${companies.size() > 0}">
</c:if>
This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt
instead of >
.
<c:if test="${companies.size() gt 0}">
</c:if>
If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length()
function then. From the documentation:
length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.
Put this at the top of JSP page to allow the fn
namespace:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Or if you're using JSPX or Facelets:
<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">
And use like this in your page:
<p>The length of the companies collection is: ${fn:length(companies)}</p>
So to test with length of a collection:
<c:if test="${fn:length(companies) gt 0}">
</c:if>
Alternatively, for this specific case you can also simply use the EL empty
operator:
<c:if test="${not empty companies}">
</c:if>
As suggested by @Joel and @Mark Chorley in earlier comments:
${empty companies}
This checks for null and empty lists/collections/arrays. It doesn't get you the length but it satisfies the example in the OP. If you can get away with it this is just cleaner than importing a tag library and its crusty syntax like gt
.
You can use like this
${fn:length(numList)}