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 119 views
119 views asked Sep 2, 2022 by avibootz
1 answer 133 views
2 answers 230 views
230 views asked Nov 6, 2021 by avibootz
1 answer 215 views
1 answer 163 views
2 answers 188 views
...