Java – How to add elements at the beginning and end of LinkedList ?

In this article, we will discuss how to add elements to LinkedList at the beginning/start & end

1. Add elements to LinkedList :

There are 2 methods available in the LinkedList class which can be used to insert/append specific element at the beginning or end of the List

  • addFirst() – Inserts the specified element at the beginning of the invoking list
  • addLast() – Appends the specified element to the end of the invoking list

2. Examples to add elements to LinkedList :

  • In the below illustration, initially we have LinkedList with 5 elements
  • 1st operation
    • add one element at the beginning or start of the LinkedList using addFirst() method
    • Now, LinkedList will have 6 elements
  • 2nd operation
    • add one element to the end of the LinkedList using addLast() method
    • Now, LinkedList will have 7 elements
  • Print elements of the LinkedList
    1. original elements
    2. after inserting 1 element at the beginning of the List
    3. after appending 1 element to the end of List

AddElementsToLinkedList.java

package in.bench.resources.java.conversion;

import java.util.LinkedList;

public class AddElementsToLinkedList {

	public static void main(String[] args) {

		// 1. create LinkedList of String elements
		LinkedList<String> fruits = new LinkedList<String>();


		// 1.1 add fruits to LL
		fruits.add("Mangoes");
		fruits.add("Apples");
		fruits.add("Grapes");
		fruits.add("Banana");
		fruits.add("Cherries");


		// 1.2 print to console
		System.out.println("Original LinkedList elements :- \n"
				+ fruits);


		// 2. add element to LinkedList at FIRST position
		fruits.addFirst("Berries");


		// 2.1 print to console
		System.out.println("\n\nAfter adding element to LinkedList at FIRST position :- \n"
				+ fruits);


		// 3. add element to LinkedList at LAST position
		fruits.addLast("Oranges");


		// 3.1 print to console
		System.out.print("\n\nAfter adding element to LinkedList at LAST position :- \n"
				+ fruits);
	}
}

Output :

Original LinkedList elements :- 
[Mangoes, Apples, Grapes, Banana, Cherries]


After adding element to LinkedList at FIRST position :- 
[Berries, Mangoes, Apples, Grapes, Banana, Cherries]


After adding element to LinkedList at LAST position :- 
[Berries, Mangoes, Apples, Grapes, Banana, Cherries, Oranges]

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java 8 – How to convert String to ArrayList ?
Java – How to convert LinkedList to ArrayList ?