Count the number of items in a List in Java
This post will discuss how to count the number of items in a List in Java.
1. Using List.size() method
The standard solution to find the number of elements in a Collection in Java is calling its size() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; class Main { public static void main(String[] args) { List<Integer> l = IntStream.range(0, 100).boxed().collect(Collectors.toList()); int count = l.size(); System.out.println(count); // 100 } } |
2. Using Stream API
With Java 8 Stream API, you can get a sequential stream over the list’s elements and call the count() method to get the count of elements in the stream.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; class Main { public static void main(String[] args) { List<Integer> l = IntStream.range(0, 100).boxed().collect(Collectors.toList()); long count = l.stream().count(); System.out.println(count); // 100 } } |
3. Using Array.getLength() method
Another plausible way involves using Reflection. The idea is to convert the list into an array and call the Array.getLength() method to get its length. The toArray() method can be used to return an array containing all the elements in the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.lang.reflect.Array; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; class Main { public static void main(String[] args) { List<Integer> l = IntStream.range(0, 100).boxed().collect(Collectors.toList()); int count = Array.getLength(l.toArray()); System.out.println(count); // 100 } } |
4. Using .length property
Alternatively, after converting the list into an array, you can directly access the .length property of the array, which returns the length of the array object.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; class Main { public static void main(String[] args) { List<Integer> l = IntStream.range(0, 100).boxed().collect(Collectors.toList()); int count = l.toArray().length; System.out.println(count); // 100 } } |
That’s all about counting the number of items in a List in Java.
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 :)