ListUtils.size()

Several times recently I had a need where I needed to know if a List, contained at least X elements. The list could be null, empty or any size imaginable. However, I only wanted to act if it contained at least X elements.

After thinking about it for a few minutes, I pulled out my ListUtils class I had created and added a new method. I created a new size() static method that would return 0 if the list was null, otherwise, return List::size() value to indicate the size of the list. A simple method that would save me a lot of redundant code.

Of course I could have something like this:

if(ListUtils.notEmpty(myList) && myList.size > X) {
    ....
}

However I find this easier to read follow and just a little simpler:

if(ListUtils.size(myList) > X) {
    ....
}

As I said this isn’t rocket science. Just a simple couple lines for the method:

 /**
     * Returns the number of elements in the list.  Checks for Null.
     * @param list List to check
     * @param <E> List Type
     * @return int indicating the number of elements or 0 if null.
     */
    public static <E> int size( List<E> list) {
        if(list == null) {
            return 0;
        }
        return list.size();
    }

For the complete implementation of my this class check out this GIST.

Ghostprogrammer
  • Ghostprogrammer
  • I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: