Write a Java Program to Merge two queues


The Java code demonstrates how to merge two queues using the addAll() method in combination with LinkedList to create and store elements in the merged queue.

  • Two Queue interfaces are implemented using the LinkedList class to create two separate queues, queue1 and queue2, to store integers.
  • Several integer elements (10, 20, 30) are added to queue1 using the add() method.
  • Several integer elements (40, 50, 60) are added to queue2 using the add() method.
  • A new Queue called mergedQueue is created to store the merged elements.
  • The addAll() method is used to merge the elements of queue1 and queue2 into mergedQueue.
  • The merged queue is printed using System.out.println().

Source Code

import java.util.LinkedList;
import java.util.Queue;
 
public class QueueMerge
{
	public static void main(String[] args)
	{
		Queue<Integer> queue1 = new LinkedList<>();
		Queue<Integer> queue2 = new LinkedList<>();
 
		// Adding elements to queue1
		queue1.add(10);
		queue1.add(20);
		queue1.add(30);
 
		// Adding elements to queue2
		queue2.add(40);
		queue2.add(50);
		queue2.add(60);
 
		// Merging two queues
		Queue<Integer> mergedQueue = new LinkedList<>();
		mergedQueue.addAll(queue1);
		mergedQueue.addAll(queue2);
 
		System.out.println("Merged queue:");
		System.out.println(mergedQueue);
    }
}
 

Output

Merged queue:
[10, 20, 30, 40, 50, 60]

Example Programs