Find first and last element of ArrayList in java
Prerequisite: ArrayList in Java Given an ArrayList, the task is to get the first and last element of the ArrayList in Java, Examples:
Input: ArrayList = [1, 2, 3, 4]
Output: First = 1, Last = 4
Input: ArrayList = [12, 23, 34, 45, 57, 67, 89]
Output: First = 12, Last = 89
- Get the ArrayList with elements.
- Get the first element of ArrayList with use of get(index) method by passing index = 0.
- Get the last element of ArrayList with use of get(index) method by passing index = size – 1.
Below is the implementation of the above approach:
ArrayList<Integer> list =
System.out.print("ArrayList: " + list);
first = list.get(
last = list.get(list.size() -
System.out.println("\nFirst : " + first
+ ", Last : " + last);
ArrayList: [1, 2, 3, 4]
First : 1, Last : 4
Time Complexity: O(1)
Auxiliary Space: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!