How to use PriorityQueue with inline comparator based on length of String in Java

1 Answer

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

public class MyClass {
    public static void main(String args[]) {
        PriorityQueue<String> pq = new PriorityQueue<String>(6, (a,b) -> a.length() - b.length());
        
        pq.add("javascript");
        pq.add("1234");
        pq.add("python");
        pq.add("c");
        pq.add("java");
        pq.add("c++");
        
        Iterator<String> 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:
   
c 1234 c++ javascript java python 
size: 6
c c++ java 1234 python javascript 
size: 0
   
*/

 



answered Nov 6, 2021 by avibootz

Related questions

1 answer 121 views
121 views asked Sep 2, 2022 by avibootz
1 answer 135 views
2 answers 233 views
233 views asked Nov 6, 2021 by avibootz
1 answer 217 views
1 answer 164 views
2 answers 189 views
...