prority queue in java code example

Example 1: java queue

import java.util.*;

Queue<Integer> queue = new LinkedList<Integer>();
// use non-primative types when constructing

// to add a value to the back of queue:
queue.add(7);

// to remove and return front value:
int next = queue.remove();

// to just return front value without removing:
int peek = queue.peek();

Example 2: priority queue in java

import java.util.PriorityQueue;
import java.util.Iterator;

class Main {
    public static void main(String[] args) {

        // Creating a priority queue
        PriorityQueue<Integer> numbers = new PriorityQueue<>();
        numbers.add(4);
        numbers.add(2);
        numbers.add(1);
        System.out.print("PriorityQueue using iterator(): ");

        //Using the iterator() method
        Iterator<Integer> iterate = numbers.iterator();
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}

Tags:

Java Example