Find size of a Java Collection (Set, List, Map, etc)
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Collection; import java.util.Set; public class Main { public static void main(String[] args) { Collection<Integer> collection = Set.of(4, 2, 3, 1, 5); System.out.println("The collection contains " + collection.size() + " elements"); } } |
Output:
The collection contains 5 elements
Note that an exception will be thrown for a null input.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.Collection; public class Main { public static void main(String[] args) { Collection<Integer> collection = null; System.out.println("The collection contains " + collection.size() + " elements"); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import org.apache.commons.collections4.CollectionUtils; import java.util.Collection; import java.util.Set; public class Main { public static void main(String[] args) { Collection<Integer> collection = Set.of(4, 2, 3, 1, 5); int size = CollectionUtils.size(collection); System.out.println("The collection contains " + size + " elements"); } } |
Output:
The collection contains 5 elements
The following code demonstrates how this method tries to handle null input gracefully.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.apache.commons.collections4.CollectionUtils; import java.util.Collection; public class Main { public static void main(String[] args) { Collection<Integer> collection = null; int n = CollectionUtils.size(collection); System.out.println("The collection contains " + n + " elements"); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Collection; import java.util.List; public class Main { public static void main(String[] args) { Collection<Integer> collection = List.of(4, 2, 3, 1, 5); long n = collection.stream().count(); System.out.println("The collection contains " + n + " elements"); } } |
Output:
The collection contains 5 elements
That’s all about finding the size of a Java Collection.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)