user2323036
user2323036

Reputation: 1585

Utility to check null and return size as 0 if empty for a collection/list in java

I have list which can be null sometimes, the return type should be int ex:

int size = 0; 
if(list != null) {
    size = list.size;
} 

Could you please let me know whether any utility is available?

Thanks.

Upvotes: 4

Views: 12697

Answers (7)

Kalai
Kalai

Reputation: 543

Not an utility; Just another approach which might help with code coverage: Optional can be used.

Optional.ofNullable(inputList)
        .orElse(Collections.emptyList())
        .size()

Note:

Collection.emptyList() of java.util does not create a new dedicated list, which is suitable for this use case.

From the doc:

Implementations of this method need not create a separate List object for each call. Using this method is likely to have comparable cost to using the like-named field.

Useful if you are forced to scrutinise code coverage (branch); Jacoco does not seem to flag any branches via this soln.

Upvotes: 0

Edward Falk
Edward Falk

Reputation: 10083

While the accepted answer is arguably the best answer, I find typing it all the time to be tedious. I wound up writing these two tiny utilities:

static int csize(Collection<?> c) { return c != null ? c.size() : 0; }
static int csize(Map<?> m) { return m != null ? m.size() : 0; }

and now I use e.g.:

int size = csize(list);

Upvotes: 0

Sam Fu
Sam Fu

Reputation: 11

with the help of Goole guava, you case use CollectionUtils.size() function

import org.apache.commons.collections.CollectionUtils;


// Test case:

// 0
int size = CollectionUtils.size(null);
//2
int size2 = CollectionUtils.size(Lists.newArrayList(2,3));

Upvotes: 0

Kenston Choi
Kenston Choi

Reputation: 2942

org.apache.commons.collections4.CollectionUtils#size(Object object) returns the following:

the size of the specified collection or 0 if the object was null

It handles the following:

  • Collection - the collection size
  • Map - the map size
  • Array - the array size
  • Iterator - the number of elements remaining in the iterator
  • Enumeration - the number of elements remaining in the enumeration

Personally, I hope the parameter type is at least Collection instead of Object for added compile-time safety. As it can throw the ff. exception:

IllegalArgumentException - thrown if object is not recognized

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

Instead of using a null value you can use Collections.emptyList()

That way you have just

private List<String> list = Collections.<String>emptyList();

int size = list.size(); // list is never null, but could be an empty list.

Upvotes: 1

TofuBeer
TofuBeer

Reputation: 61536

Roll your own, put it in a method, preferably in a class. Something like:

public class CollectionUtils
{
    private CollectionUtils()
    {
    }

    public static getSize(final List<?> list)
    {
        // I try to make all my variables final, and I have a dislike of the ternary (?:)    
        // operator...
        final int size;

        if(list == null)
        {
            size = 0;
        }
        else
        {
            size = list.size();
        }

        return (size);
     }
 }

By putting it in a method if you find a better way to do it later you can update the code only in one place. If the language were to change in some way in the future as well, say some odd thing like ?list.size() that returns 0 if it is null or the size if it is not null then you could simply delete the method and update all of the places that call it to be the new way of calling the method.

Upvotes: 1

arshajii
arshajii

Reputation: 129517

What about

int size = (list == null) ? 0 : list.size();

I'm not sure why you would want a utility for this, since the above seems simple enough.

Upvotes: 7

Related Questions