Get first and last elements from ArrayList Java

Problem Statement: Write a Java program to get first and last elements from ArrayList.

Here’s a Java program that demonstrates how to get the first and last elements from an ArrayList,

package com.javacodepoint.collection;

import java.util.ArrayList;

public class GetFirstAndLastElementsDemo {
	
	public static void main(String[] args) {
		// Create an ArrayList of integers
		ArrayList<Integer> numbers = new ArrayList<>();

		// Add some elements to the ArrayList
		numbers.add(10);
		numbers.add(20);
		numbers.add(30);
		numbers.add(40);
		numbers.add(50);

		// Check if the ArrayList is not empty
		if (!numbers.isEmpty()) {
			// Get the first element (element at index 0)
			int firstElement = numbers.get(0);

			// Get the last element (element at index size-1)
			int lastIndex = numbers.size() - 1;
			int lastElement = numbers.get(lastIndex);

			// Print the first and last elements
			System.out.println("First Element: " + firstElement);
			System.out.println("Last Element: " + lastElement);
		} else {
			System.out.println("The ArrayList is empty.");
		}
	}
}

OUTPUT:

First Element: 10
Last Element: 50

Explanation:

  1. Creating the ArrayList: We start by creating an ArrayList named numbers to store a list of integers.
  2. Adding Elements: We add some integer elements (10, 20, 30, 40, 50) to the numbers ArrayList using the add method.
  3. Checking if the ArrayList is Not Empty: Before getting the first and last elements, we check if the ArrayList is not empty using the isEmpty method. This is important because trying to access elements from an empty ArrayList would result in an error.
  4. Getting the First Element: If the ArrayList is not empty, we use the get(0) method to get the first element, which is located at index 0. In this case, firstElement will be set to 10.
  5. Getting the Last Element: To get the last element, we first calculate the index of the last element by subtracting 1 from the size of the ArrayList (numbers.size() - 1). In this case, the last element is located at index 4. Then, we use the get(lastIndex) method to get the value of the last element, which is 50.
  6. Printing the Results: Finally, we print the first and last elements to the console using System.out.println().

By following these steps, the program effectively retrieves and displays the first and last elements from the ArrayList. It also includes a check to handle cases where the ArrayList might be empty, ensuring that the program doesn’t encounter any errors in such situations.

See also: Convert an ArrayList of strings into a string array.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *