How to Get a Size of Collection in Java?
Given a Collection in Java, the task is to find the length or size of the collection.
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: Array_List: [1, 2, 3,4] Output: 4 Input: Linked_List: [geeks, for, geeks] Output: 3
The Size of the different collections can be found with the size() method. This method returns the number of elements in this collection. This method does not take any parameters.
Below is the Implementation:
Example 1:
Java
// Java program to demonstrate// size() method of collection import java.util.*; public class Example1 { public static void main(String[] args) { // Creating object of List<Integer> List<Integer> Array_List = new ArrayList<Integer>(); // add elements Array_List.add(1); Array_List.add(2); Array_List.add(3); Array_List.add(3); // getting total size of list // using size() method int size = Array_List.size(); // print the size of list System.out.println("Size of list = " + size); // print list System.out.println("Array_List = " + Array_List); }} |
Size of list = 4 Array_List = [1, 2, 3, 3]
Example 2:
Java
// Java program to demonstrate// size() method of Collectionimport java.util.*;import java.io.*; class Example2 { public static void main(String[] args) { // Creating object of LinkedList<Integer> LinkedList<String> al = new LinkedList<String>(); // Populating LinkedList al.add("GEEKS"); al.add("FOR"); al.add("GEEKS"); // getting total size of Linkedlist // using size() method int size = al.size(); // print the size System.out.println("Size of the linkedlist = " + size); // print Linkedlist System.out.println("Linkedlist = " + al); }} |
Size of the linkedlist = 3 Linkedlist = [GEEKS, FOR, GEEKS]

