Write a Java program to Find the minimum element in a queue without removing it from the queue
The Java code defines a class QueueMinElement with a method findMinElement that finds the minimum element in a given Queue of integers.
- The findMinElement method takes a Queue<Integer> named queue as input and returns an integer representing the minimum element.
- Before processing the queue, the method checks if the queue is empty using the isEmpty() method. If the queue is empty, it throws a NoSuchElementException with the message "Queue is empty".
- The method initializes a variable min to the maximum possible integer value (Integer.MAX_VALUE). This is done to ensure that any element in the queue will be smaller than the initial min.
- The method 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 min. If num is smaller than min, the value of min is updated to num.
- After the loop finishes, the variable min will hold the minimum element in the queue.
- The method returns the value of min.
- In the main method, a Queue<Integer> named queue is created using the LinkedList implementation of the Queue interface. Elements (integers) are added to the queue using the offer() method.
- The findMinElement method is then called with the queue as an argument, and the minimum element returned by the method is stored in the variable minElement.
- Finally, the minimum element is printed using System.out.println().
Source Code
import java.util.*;
public class QueueMinElement
{
public static int findMinElement(Queue<Integer> queue)
{
if (queue.isEmpty())
{
throw new NoSuchElementException("Queue is empty");
}
int min = Integer.MAX_VALUE;
for (int num : queue)
{
if (num < min)
{
min = num;
}
}
return min;
}
public static void main(String[] args)
{
Queue<Integer> queue = new LinkedList<>();
queue.offer(50);
queue.offer(20);
queue.offer(80);
queue.offer(30);
queue.offer(60);
int minElement = findMinElement(queue);
System.out.println("Minimum element in the queue : " + minElement);
}
}
Output
Minimum element in the queue : 20