To get the length of a list in Java, you can use the size()
method of the List interface.
In this example,
numbers
with integer values.size()
method of the list object numbers
to get the number of elements in the list.size()
method returns the number of elements in the list.System.out.println()
.import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int length = numbers.size();
System.out.println("Length of the list is: " + length);
}
}
Length of the list is: 5
In this example,
fruits
with string values.size()
method of the list object fruits
to get the number of elements in the list.size()
method returns the number of elements in the list.System.out.println()
.import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "banana", "cherry");
int length = fruits.size();
System.out.println("Length of the list is: " + length);
}
}
Length of the list is: 3
In this tutorial, we learned How to Get Length of a List in Java language with well detailed examples.