Write a Java program to get the first and last occurrence of the specified elements in a linked list


This Java code demonstrates how to use the getFirst() and getLast() methods to retrieve the first and last elements of a linked list, respectively.

  • The code defines a class named GetElement_FirstLast with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a new LinkedList object named fru_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Guava", "Papaya", "Mulberry", etc., are added to the fru_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the initial contents of the fru_list before any modifications.
  • The getFirst() method is called on the fru_list to retrieve the first element of the linked list. The returned value is assigned to an Object variable named f_ele.
  • The System.out.println statement is used to print the value of f_ele, which represents the first element of the linked list.
  • The getLast() method is called on the fru_list to retrieve the last element of the linked list. The returned value is assigned to an Object variable named l_ele.
  • The System.out.println statement is used to print the value of l_ele, which represents the last element of the linked list.
  • The output of the program will be the initial contents of the fru_list printed on the first line, followed by the first and last elements of the list printed on the subsequent lines, as retrieved by the getFirst() and getLast() methods, respectively.

Source Code

import java.util.LinkedList;
import java.util.Iterator;
public class GetElement_FirstLast
{
	public static void main(String[] args)
	{
		LinkedList<String> fru_list = new LinkedList<String>();
		fru_list.add("Guava");
		fru_list.add("Papaya");
		fru_list.add("Mulberry");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon");
		fru_list.add("Pineapple");
		System.out.println("Given linked list :" + fru_list);  
		Object f_ele = fru_list.getFirst();
		System.out.println("First Element : "+f_ele);
		Object l_ele = fru_list.getLast();
		System.out.println("Last Element : "+l_ele);
	}
}

Output

Given linked list :[Guava, Papaya, Mulberry, Apple, Banana, Cherry, Watermelon, Pineapple]
First Element : Guava
Last Element : Pineapple

Example Programs