To get the first element in a Java List, you can use the get method with index 0.
In this example,
numbers
with integer elements.get
method with index 0.get
method returns the element at the specified index.import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
int firstElement = numbers.get(0);
System.out.println("First element is: " + firstElement);
}
}
First element is: 10
In this example,
names
with string elements.get
method with index 0.get
method returns the element at the specified index.import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
String firstElement = names.get(0);
System.out.println("First element is: " + firstElement);
}
}
First element is: Alice
In this tutorial, we learned How to get First Element in a List in Java language with well detailed examples.