How to Get the First and Last Element from LinkedList in Java


In this example, we will learn how to get first and last element from LinkedList with getFirst and getLast methods in Java.

Source Code

package com.beginner.examples;

import java.util.LinkedList;

public class GetFirstAndLastElementOfLinkedList {

	public static void main(String[] args) {

		LinkedList ll = new LinkedList();

		ll.add("a");
		ll.add("b");
		ll.add("c");
		ll.add("d");

		// Use the getFirst() method in the LinkedList class
		String fristElement = ll.getFirst();

		// Use the getLast() method in the LinkedList class
		String lastElement = ll.getLast();

		System.out.println("First element:" + fristElement + "nLast element:"
				+ lastElement);

	}

}

Output:

First element:a
Last element:d

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments