How to use PriorityQueue in Java

2 Answers

0 votes
import java.util.Iterator;
import java.util.PriorityQueue;

public class MyClass {
    public static void main(String args[]) {
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10);

        pq.add(120);
        pq.add(85);
        pq.add(99);
        pq.add(50);
        pq.add(89);
        pq.add(11);
        pq.add(8);
        
        Iterator<Integer> itr = pq.iterator();
        while(itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
        
        System.out.println("\nsize: " + pq.size());

        Integer head = pq.peek();
        System.out.println("head: " + head); 

        head = pq.poll(); 
        head = pq.peek();
       
        System.out.println("head = pq.poll(); head : " + head);
        System.out.println("size: " + pq.size());
        
        while (!pq.isEmpty()) {
            System.out.print(pq.poll() + " ");
        }
        
        System.out.println("\nsize: " + pq.size());
    }
}
   
   
   
   
/*
run:
   
8 85 11 120 89 99 50 
size: 7
head: 8
head = pq.poll(); head : 11
size: 6
11 50 85 89 99 120 
size: 0
   
*/

 



answered Nov 6, 2021 by avibootz
0 votes
import java.util.PriorityQueue;
import java.util.Iterator;
 
public class MyClass {
    public static void main(String args[]) {
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(6, (a,b) -> a - b);
         
        pq.add(7686);
        pq.add(98763);
        pq.add(234);
        pq.add(120);
        pq.add(9);
        pq.add(98);

        Iterator<Integer> itr = pq.iterator();
        while(itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
          
        System.out.println("\nsize: " + pq.size());
         
        while (!pq.isEmpty()) {
            System.out.print(pq.poll() + " ");
        }
         
        System.out.println("\nsize: " + pq.size());
    }
}
    
    
    
    
/*
run:
    
9 120 98 98763 234 7686 
size: 6
9 98 120 234 7686 98763 
size: 0
    
*/

 



answered Nov 7, 2021 by avibootz

Related questions

1 answer 132 views
1 answer 163 views
2 answers 188 views
1 answer 95 views
...