Related Articles

Related Articles

How to Get a Size of Collection in Java?
  • Last Updated : 15 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output

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

Example 2: 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output

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

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :