Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Get First and Last Elements from an Array List


In this article, we will understand how to get first and last elements from an array list. A list is an ordered collection that allows us to store and access elements sequentially. It contains the index-based methods to insert, update, delete and search the elements. It can also have the duplicate elements.

Below is a demonstration of the same −

Suppose our input is

Input list: [40, 60, 150, 300]

The desired output would be

The first element is : 40
The last element is : 300

Algorithm

Step 1 - START
Step 2 - Declare ArrayList namely input_list.
Step 3 - Define the values.
Step 4 - Check of the list is not an empty list. Use the .get(0) and .get(list.size - 1) to get the first
and last elements.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.ArrayList;
public class Demo {
   public static void main(String[] args){
      ArrayList<Integer> input_list = new ArrayList<Integer>(5);
      input_list.add(40);
      input_list.add(60);
      input_list.add(150);
      input_list.add(300);
      System.out.print("The list is defined as: " + input_list);
      int first_element = input_list.get(0);
      int last_element = input_list.get(input_list.size() - 1);
      System.out.println("\nThe first element is : " + first_element);
      System.out.println("The last element is : " + last_element);
   }
}

Output

The list is defined as: [40, 60, 150, 300]
The first element is : 40
The last element is : 300

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

import java.util.ArrayList;
public class Demo {
   static void first_last(ArrayList<Integer> input_list){
      int first_element = input_list.get(0);
      int last_element = input_list.get(input_list.size() - 1);
      System.out.println("\nThe first element is : " + first_element);
      System.out.println("The last element is : " + last_element);
   }
   public static void main(String[] args){
      ArrayList<Integer> input_list = new ArrayList<Integer>(5);
      input_list.add(40);
      input_list.add(60);
      input_list.add(150);
      input_list.add(300);
      System.out.print("The list is defined as: " + input_list);
      first_last(input_list);
   }
}

Output

The list is defined as: [40, 60, 150, 300]
The first element is : 40
The last element is : 300