Sunday, June 17, 2018

Queue Interface in Java with Examples

Queue interface is the part of Collection interface which store the elements at the last of the list and deleting the elements from first of the list so it orders the element in FIFO (First in First Out) manner.
Since it is a interface, we need a concrete class during its declaration. So it has two classes to initialize a Queue object.

           PriorityQueue
           LinkedList

Syntax:
Queue  <E> q = new LinkedList <E> ();
Queue  <E> q = new PriorityQueue <E> ();

Note:  E is the generic object type of the Queue Interface.

Operations on Queue:

-Add():  Add an element at the last (tail) of the Queue.
-peek(): Retrieves head of the Queue, it return null if queue is empty.
-element():  It is similar to peek method. Throws  NoSuchElementException if queue is empty.
-poll(): It is remove and return the head of the queue. It return null if queue is empty.
-remove(): It is remove and return the head of the queue. It return NoSuchElementException if queue is empty.

Sample Program of Queue:

package blogPkg;

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample1 {

      public static void main(String[] args) {
           
            Queue <String> q = new LinkedList <String>();
           
            //Adding element in the queue
            q.add("John");
            q.add("Dennis");
            q.add("Javed");
            q.add("Eric");
           
            System.out.println("Element of the Queue:"+ q);
           
            // fetch first element of the queue using peek method
            System.out.println(q.peek());
           
            // fetch first element of the queue using element method
            System.out.println(q.element());
           
            //remove first element of the queue using remove method
            System.out.println(q.remove()); // remove John
           
            //remove first element of the queue using poll method
            System.out.println(q.poll()); // remove Dennis
           
            System.out.println("After done different operations check element of the queue:"+ q);
           
            //get size of the queue
            int size = q.size();
            System.out.println("Size of Queue:" + size);
           
           
      }

}


Output: Element of the Queue:[John, Dennis, Javed, Eric]
John
John
John
Dennis
After done different operations check element of the queue:[Javed, Eric]
Size of Queue:2




                                                                              HashSet class with Example
                                                                              LinkedHashSet class with Example
                                                                              TreeSet class with Example





No comments:

Post a Comment