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> 

4 Answers

<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="" %> 

Or if you're using JSPX or Facelets:

<... xmlns:fn=""> 

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> 
6

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)} 

use ${fn:length(companies) > 0} to check the size. This returns a boolean

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like