Open In App

How to Get a Size of Collection in Java?

Last Updated : 15 Oct, 2020
Suggest changes
Share
Like Article
Like
Report

Given a Collection in Java, the task is to find the length or size of the collection.

Examples:

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);  } } 

Output
Size of list = 4 Array_List = [1, 2, 3, 3]

Example 2: 

Java
// Java program to demonstrate // size() method of Collection import 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);  } } 

Output
Size of the linkedlist = 3 Linkedlist = [GEEKS, FOR, GEEKS]

Explore