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);
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);
}
}
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;
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!