Write a Java program to Find the Longest string in the queue


The Java code defines a class QueueLongestString with a method findLongestString that finds the longest string in a given Queue of strings.

  • The findLongestString method takes a Queue<String> named queue as input and returns a string representing the longest string in the queue.
  • 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 longestString to an empty string. This variable will be used to store the longest string found in the queue.
  • 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 str takes the value of the current element from the queue.
  • Inside the loop, the code checks if the length of the current str is greater than the length of the longestString. If str is longer than longestString, it updates the value of longestString to str.
  • After the loop finishes, the variable longestString will hold the longest string in the queue.
  • The method returns the value of longestString.
  • In the main method, a Queue<String> named queue is created using the LinkedList implementation of the Queue interface. Strings are added to the queue using the offer() method.
  • The original queue is printed using System.out.println().
  • The findLongestString method is then called with the queue as an argument, and the longest string returned by the method is stored in the variable longestString.
  • Finally, the longest string in the queue is printed using System.out.println().

Source Code

import java.util.*;
 
public class QueueLongestString
{
	public static String findLongestString(Queue<String> queue)
	{
		if (queue.isEmpty())
		{
			throw new NoSuchElementException("Queue is empty");
		}
 
		String longestString = "";
		for (String str : queue)
		{
			if (str.length() > longestString.length())
			{
				longestString = str;
			}
		}
 
		return longestString;
	}
 
	public static void main(String[] args)
	{
		Queue<String> queue = new LinkedList<>();
		queue.offer("Apple");
		queue.offer("Pineapple");
		queue.offer("Banana");
		queue.offer("Cherry");
		queue.offer("Watermelon");
		System.out.println("Original Queue : " + queue);
 
		String longestString = findLongestString(queue);
		System.out.println("Longest String in the Queue : " + longestString);
	}
}
 

Output

Original Queue : [Apple, Pineapple, Banana, Cherry, Watermelon]
Longest String in the Queue : Watermelon

Example Programs