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;

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap