Java PriorityQueue create with custom Comparator

Description

Java PriorityQueue create with custom Comparator

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

enum Level {
  High, Medium, Low/*from  w w w .j a va2  s. c o m*/
}

class Language implements Comparable<Language> {
  private String name;

  private Level priority;

  public Language(String str, Level pri) {
    name = str;
    priority = pri;
  }

  public String getName() {
    return name;
  }

  public Level getPriority() {
    return priority;
  }

  public int compareTo(Language msg2) {
    return priority.compareTo(msg2.priority);
  }
}

class MessageComparator implements Comparator<Language> {
  public int compare(Language msg1, Language msg2) {
    return msg2.getPriority().compareTo(msg1.getPriority());
  }
}

public class Main {
  public static void main(String args[]) {

    PriorityQueue<Language> pq = new PriorityQueue<Language>(3);

    pq.add(new Language("CSS", Level.Low));
    pq.add(new Language("HTML", Level.High));
    pq.add(new Language("Java", Level.Medium));
    Language m;
    while ((m = pq.poll()) != null)
      System.out.println(m.getName()+ " Priority: " + m.getPriority());

    PriorityQueue<Language> pqRev = new PriorityQueue<Language>(3, new MessageComparator());

    pqRev.add(new Language("Javascript", Level.Low));
    pqRev.add(new Language("SQL", Level.High));
    pqRev.add(new Language("F", Level.Medium));

    while ((m = pqRev.poll()) != null)
      System.out.println(m.getName() + " Priority: " + m.getPriority());
  }
}



PreviousNext

Related