Java - Collection Framework Priority Queues

Introduction

A priory queue is a queue in which each element has an associated priority.

The element with the highest priority is removed next from the queue.

Java provides PriorityQueue as an implementation class for an unbounded priority queue.

You can use natural order of the elements of the queue as its priority.

In this case, the elements of the queue must implement the Comparable interface.

You can also supply a Comparator object, which will determine the priority order of the elements.

The following code adds comparable person to a priory queue.

Demo

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

public class Main {
  public static void main(String[] args) {
    Queue<ComparablePerson> pq = new PriorityQueue<>();
    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();//from www.ja va 2s .c o m
      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 Topics