Write a Java Program to Find the maximum element in a queue
The Java code finds the maximum element in the Queue named queue. Here's how the code works:
- A queue of integers named queue is created using the LinkedList implementation of the Queue interface.
- Elements (integers) are added to the queue.
- The code initializes a variable maxElement to the minimum possible integer value (Integer.MIN_VALUE). This is done to ensure that any element in the queue will be greater than the initial maxElement.
- The code then iterates through the elements of the queue using an enhanced for loop (also known as a "for-each" loop). In each iteration, the variable num takes the value of the current element from the queue.
- Inside the loop, the code compares num with the current maxElement. If num is greater than maxElement, the value of maxElement is updated to num.
- After the loop finishes, the variable maxElement will hold the maximum element in the queue.
- The maximum element is then printed using System.out.println().
Source Code
import java.util.LinkedList;
import java.util.Queue;
public class QueueMaxElement
{
public static void main(String[] args)
{
Queue<Integer> queue = new LinkedList<>();
// Adding elements to the queue
queue.add(10);
queue.add(30);
queue.add(50);
queue.add(20);
queue.add(40);
// Finding the maximum element in the queue
int maxElement = Integer.MIN_VALUE;
for (int num : queue)
{
if (num > maxElement)
{
maxElement = num;
}
}
System.out.println("Maximum Element in the Queue : " + maxElement);
}
}
Output
Maximum Element in the Queue : 50