How to find the Length of ArrayList in Java


Example 1: Using size() method

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("PHP");
int sizeOfArrayList = list.size();

System.out.println("ArrayList Size: " + sizeOfArrayList);

ArrayList Size: 3


Example 2: Using Stream API

public class ArrayListSize {
    public static void main(String[] args) {

        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("USA");
        arrayList.add("China");
        arrayList.add("Canada");
        arrayList.add("Japan");
        arrayList.add("France");

        long count = arrayList.stream().count();
        System.out.println("ArrayList Size: " + count);


    }
}

ArrayList Size: 5

One should not do this unless there is a need to integrate over the ArrayList, use a for/while loop to get the count.

ArrayList<String> dataList = new ArrayList<>();
dataList.add(...)
...
...

int size = 0;
for (String element: list) {
    size++;
   //some logic
}
int length = count;
-




Have Questions? Post them here!