How do I find the size of a Java list?

JavaObject Oriented ProgrammingProgramming

List provides a method size() to get the count of elements currently present in 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.

Example

Following example shows how to check 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));
System.out.println("List: " + list);
      System.out.println("List size: " + list.size());
list.add(4);
      list.add(5);
      list.add(6);
      System.out.println("List: " + list);
      System.out.println("List size: " + list.size());
list.remove(1);
      System.out.println("List: " + list);
      System.out.println("List size: " + list.size());
   }
}

Output

This will produce the following result −

List: [1, 2, 3]
List size: 3
List: [1, 2, 3, 4, 5, 6]
List size: 6
List: [1, 3, 4, 5, 6]
List size: 5
raja
Updated on 09-May-2022 13:58:00

Advertisements