Write a Java program to Add LinkedList collection into another LinkedList collection on the specified index


The code demonstrates how to use the addAll method of LinkedList in Java to add all elements from one list to another list at a specified index.

In the AddList_ToAnotherList class, two LinkedList objects are created: f1 and f2. The f1 list is initialized with fruit names such as "Papaya", "Mulberry", "Apple", "Mango", and "Guava" using the add method. Similarly, the f2 list is initialized with fruit names such as "Banana", "Cherry", and "Watermelon" using the add method. The System.out.println statement is used to print the fruit names in the f1 list.

The addAll method is then called on the f1 list with the arguments 3 and f2. The 3 specifies the index at which the elements from f2 should be inserted in the f1 list. The f2 is the collection of elements that are added to the f1 list. The addAll method adds all elements from f2 to the f1 list at the specified index, shifting the existing elements, if any, to the right.

Finally, another System.out.println statement is used to print the fruit names in the f1 list after the elements from f2 have been added to the f1 list at the specified index using the addAll method.

Source Code

import java.util.LinkedList;
public class AddList_ToAnotherList
{
	public static void main(String[] args)
	{
		LinkedList <String> f1 = new LinkedList <String>();
		f1.add("Papaya");
		f1.add("Mulberry");
		f1.add("Apple");
		f1.add("Mango");
		f1.add("Guava");
 
		LinkedList <String> f2 = new LinkedList <String>();
		f2.add("Banana");
		f2.add("Cherry");
		f2.add("Watermelon");
 
		System.out.println("Fruit Names : " + f1);
		f1.addAll(3, f2);
		System.out.println("Fruit Names : " + f1);
	}
}

Output

Fruit Names : [Papaya, Mulberry, Apple, Mango, Guava]
Fruit Names : [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon, Mango, Guava]

Example Programs