Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,562 questions

52,727 answers

573 users

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 119 views
1 answer 141 views
2 answers 166 views
1 answer 81 views
...