How to check the Java list size?


List provides a method size() to check the current size of the list.

Syntax

int size()

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Returns

The number of elements in this list.

Example

The following example shows how to get size of a list using size() method.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4));
      System.out.println("List: " + list);
      System.out.println("List Size: " + list.size());
      list.add(5);
      list.add(6);
      list.add(7);
      System.out.println("List: " + list);
      System.out.println("List Size: " + list.size());
      list.remove(5);
      System.out.println("List: " + list);
      System.out.println("List Size: " + list.size());
   }
}

Output

This will produce the following result −

List: [1, 2, 3, 4]
List Size: 4
List: [1, 2, 3, 4, 5, 6, 7]
List Size: 7
List: [1, 2, 3, 4, 5, 7]
List Size: 6

Updated on: 09-May-2022

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements