• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Java | PriorityQueue
  1. Notes
  2. Example
  3. Example: Comparator

  1. Notes
    Objects must implement java.lang.Comparable<T> (Exception: cannot be cast to java.lang.Comparable)
    Ordered collection (java.lang.Comparable<T>)
    null elements not allowed
    Duplicates elements allowed
  2. Example
    PriorityQueue<String> pq = new PriorityQueue<>();
    
    // pq.add(null); // java.lang.NullPointerException
    pq.add("c");
    pq.add("bb");
    pq.add("bb");
    pq.add("aaa");
    pq.add("aaa");
    pq.add("aaa");
    
    while (!pq.isEmpty())
        System.out.println(pq.remove());
    
    // pq.forEach(System.out::println); // elements of the queue might be printed in a random order
    Output:
    aaa
    aaa
    aaa
    bb
    bb
    c
  3. Example: Comparator
    PriorityQueue<String> pq = new PriorityQueue<>(Comparator.comparing(String::length));
    
    // pq.add(null); // java.lang.NullPointerException
    pq.add("c");
    pq.add("bb");
    pq.add("bb");
    pq.add("aaa");
    pq.add("aaa");
    pq.add("aaa");
    
    while (!pq.isEmpty())
        System.out.println(pq.remove());
    
    // pq.forEach(System.out::println); // elements of the queue might be printed in a random order
    Output:
    c
    bb
    bb
    aaa
    aaa
    aaa
© 2025  mtitek