Java: Get Number of Elements in a List
Getting the number of elements in a list is a common operation during software development. In Java - fetching the length of a list is done via the size()
method, which accesses the cached length of the list in O(1) lookup time.
Get Number of Elements in a Java ArrayList
List<Integer> arrayList = List.of(1, 2, 3);
System.out.println(arrayList.size()); // 3
Get Number of Elements in Nested List
Sometimes though, we have nested elements, the wrappers of which can be counted as single elements. Alternatively, their constituent elements could be counted as elements instead. In the former case, the code from the previous section applies, but for the latter case we'd want to sum the sizes of each nested object.
Any object that exposes a method to return its size works - and a List
implementation such as an ArrayList
can serve as a complex type in an example. Let's create three lists, and a list containing them and check both the size of the parent list as well as the sum of the sizes of all of the lists:
List<Integer> list1 = List.of(1, 2, 3);
List<Integer> list2 = List.of(1, 2, 3);
List<Integer> list3 = List.of(1, 2, 3);
List<List<Integer>> arrayList = List.of(list1, list2, list3);
System.out.println(arrayList.size()); // 3
int size = arrayList.stream().mapToInt(x -> x.size()).sum();
System.out.println(size); // 9
Using mapToInt()
- we can map each element of a stream to an integer value. In our case, we map a stream of three lists into a stream of three integers representing their sizes. Finally, we sum()
the stream and terminate it - resulting in an int
.
Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.
Great passion for accessible education and promotion of reason, science, humanism, and progress.