How to initialize and print 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<String> pq = new PriorityQueue<>();
         
        pq.add("abcd");
        pq.add("1234");
        pq.add("12ab");
        pq.add("ab12");
        pq.add("java");
        pq.add("c++");
         
        Iterator<String> itr = pq.iterator();
        while(itr.hasNext()) {
            System.out.print(itr.next() + "\n");
        }
         
        System.out.println("\nsize: " + pq.size());
    }
}
    
    
    
    
/*
run:
    
1234
ab12
12ab
abcd
java
c++

size: 6
    
*/

 



answered Nov 6, 2021 by avibootz
edited Aug 14, 2023 by avibootz
0 votes
import java.util.PriorityQueue;
 
public class MyClass {
    public static void main(String args[]) {
        PriorityQueue<String> pq = new PriorityQueue<>();
         
        pq.add("abcd");
        pq.add("1234");
        pq.add("12ab");
        pq.add("ab12");
        pq.add("java");
        pq.add("c++");
         
        while (!pq.isEmpty()) {
            System.out.print(pq.poll() + "\n");
        }
         
        System.out.println("\nsize: " + pq.size());
    }
}
    
    
    
    
/*
run:
    
1234
12ab
ab12
abcd
c++
java

size: 0
    
*/

 



answered Nov 6, 2021 by avibootz
edited Aug 14, 2023 by avibootz

Related questions

1 answer 163 views
1 answer 95 views
1 answer 132 views
2 answers 229 views
229 views asked Nov 6, 2021 by avibootz
6 answers 289 views
...