Wednesday, July 3, 2024
HomeLanguagesJavaFind first and last element of ArrayList in java

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

Approach:

  1. Get the ArrayList with elements.
  2. Get the first element of ArrayList with use of get(index) method by passing index = 0.
  3. 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: 

Java




// Java code to find first and last element
// of ArrayList
 
import java.util.ArrayList;
 
public class GFG {
 
    // main method
    public static void main(String[] args)
    {
 
        // creating an Empty Integer ArrayList
        ArrayList<Integer> list = new ArrayList<Integer>(5);
 
        // using add() to initialize values
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
 
        // printing initial value ArrayList
        System.out.print("ArrayList: " + list);
 
        // find first element
        int first = list.get(0);
 
        // find last element
        int last = list.get(list.size() - 1);
 
        // print first and last element of ArrayList
        System.out.println("\nFirst : " + first
                           + ", Last : " + last);
    }
}


Output:

ArrayList: [1, 2, 3, 4]
First : 1, Last : 4

Time Complexity: O(1)

Auxiliary Space: O(1)

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments