Java - Using a Comparator Object in a Priority Queue

Introduction

The PriorityQueue class does not guarantee any ordering of the elements when you use an iterator.

Its toString() method uses its iterator to give you the string representation of its elements.

When we print the priority queue, its elements are not ordered according to their priority.

When using the peek() or remove() method, the correct element is peeked at or removed, which is based on the element's priority.

To use a Comparator object in a priority queue, specify your Comparator object when you create an object of the PriorityQueue class.

The following code uses a Comparator object to have a priority queue for the list of ComparablePerson.

It uses the alphabetical ordering of the name of a ComparablePerson as the criterion to determine its priority.

The person whose name comes first in the alphabetical order has higher priority.

Demo

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class Main {
  public static void main(String[] args) {
    int initialCapacity = 5;
    Comparator<ComparablePerson> nameComparator = Comparator
        .comparing(ComparablePerson::getName);

    Queue<ComparablePerson> pq = new PriorityQueue<>(initialCapacity,
        nameComparator);//from   w  w  w.  ja  va  2s  . c o  m
    pq.add(new ComparablePerson(1, "XML"));
    pq.add(new ComparablePerson(4, "Java"));
    pq.add(new ComparablePerson(2, "Javascript"));
    pq.add(new ComparablePerson(3, "Json"));
    pq.add(new ComparablePerson(4, "Oracle"));

    System.out.println("Priority queue: " + pq);

    while (pq.peek() != null) {
      System.out.println("Head Element: " + pq.peek());
      pq.remove();
      System.out.println("Removed one element from Queue");
      System.out.println("Priority queue: " + pq);
    }
  }
}

class ComparablePerson extends Person implements Comparable {
  public ComparablePerson(int id, String name) {
    super(id, name);
  }

  @Override
  public int compareTo(Object o) {
    ComparablePerson cp = (ComparablePerson) o;
    int cpId = cp.getId();
    String cpName = cp.getName();

    if (this.getId() < cpId) {
      return -1;
    }

    if (this.getId() > cpId) {
      return 1;
    }

    if (this.getId() == cpId) {
      return this.getName().compareTo(cpName);
    }

    // Should not reach here
    return 0;
  }
}

class Person {
  private int id;
  private String name;

  public Person(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof Person)) {
      return false;
    }

    // id must be the same for two Persons to be equal
    Person p = (Person) o;
    if (this.id == p.getId()) {
      return true;
    }

    return false;
  }

  @Override
  public int hashCode() {
    // A trivial implementation
    return this.id;
  }

  @Override
  public String toString() {
    return "(" + id + ", " + name + ")";
  }
}

Result

Related Topic