This post will discuss how to find the size of a Java Collection (Set, List, Map, etc.).

1. Using size() method

Since all Java Collections implement the Collection interface, they all have the size() method that returns the number of elements in the collection.

Download  Run Code

Output:

The collection contains 5 elements

 
Note that an exception will be thrown for a null input.


Output:

Exception in thread “main” java.lang.NullPointerException
    at Main.main(Main.java:8)

2. Using Apache Commons Collections

To get a null-safe version, you may use the CollectionUtils.size() method provided by Apache Commons Collections.

Download Code

Output:

The collection contains 5 elements

 
The following code demonstrates how this method tries to handle null input gracefully.

Download Code

Output:

The collection contains 0 elements

3. Using Stream.count() method

Another possibility is using Java 8 Streams. The idea is to get a stream over the elements in the collection and the count of elements in the stream using the count() method.

Download  Run Code

Output:

The collection contains 5 elements

That’s all about finding the size of a Java Collection.