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;
-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- CRUD operations in Spring Boot + JDBC
- Java Check Leap Year - Programs with Code Examples
- [fix] Java JDBC ConnectException: Connection refused
- How to add hours and minutes to Java Instant
- Java Program: Random Number Generator
- Java: The value of the local variable string is not used
- How to get list of all Java versions installed on macOS
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Java + Spring JDBC Template + Gradle Example
- Convert String to LocalDate in Java
- Remove Trailing zeros BigDecimal Java
- Java 8 Predicate Functional Interface isEqual() Method Example
- How to Hardcode Date in Java with Examples
- Java 8: Predicate negate() default Function Example
- Java: Collect Stream as ArrayList or LinkedList
- The Motivation Behind Generics in Java Programming
- How to Add/Subtract Days to the Current Date in Java
- Error: Can not find the tag library descriptor for
- Setting up JUnit 5 dependency with Maven Example
- Run Java Code Every Second
- How to create a tar.gz file using Java
- [Fix] java: integer number too large compilation error
- Java 8: Find the Max value in a List
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- Convert Java Array to ArrayList Code Example
More Posts:
- 5 Ways to Loop a Dictionary in Python - Python
- Java 8 Streams map() with examples - Java
- Generate SHA-256 Hash and Salt in Java Example - Java
- Convert Java Object to XML using Jackson Library - Java
- How to update Cargo (Rust Lang) - Rust
- How to show Machintosh HD icon on Mac Desktop - MacOS
- How to lock Notepad++ tabs? - NotepadPlusPlus
- Fix [Mac Terminal] The operation couldn’t be completed. Unable to locate a Java Runtime. (update for Ventura/Sonoma) - Java