Junior — Middle
How to extract the first or only element from a List collection?
sobes.tech AI
Answer from AI
To get the first or only element from a List collection in Java, you can use the get(0) method. For example:
List<String> list = Arrays.asList("apple", "banana", "cherry");
String firstElement = list.get(0); // "apple"
If the list might be empty, you should check its size to avoid an IndexOutOfBoundsException:
if (!list.isEmpty()) {
String first = list.get(0);
}
To check for a single element, verify that the list size is 1:
if (list.size() == 1) {
String onlyElement = list.get(0);
}