import java.util.Comparator;
import java.util.PriorityQueue;
public class MyPriorityQueue {
public static void main(String[] args) {
Comparator<String> com = new MyComparator();
PriorityQueue<String> q = new PriorityQueue<String>(10, com);
q.add("a");
q.add("zz zz zz zz zz");
q.add("cc cc cc");
q.add("The cat in the hat");
q.add("dddd");
while (q.size() != 0) {
System.out.println(q.remove());
}
}
}
// sort by string length of string
class MyComparator implements Comparator<String> {
public int compare(String x, String y) {
if (x.length() < y.length()) {
return -1;
}
if (x.length() > y.length()) {
return 1;
}
return 0;
}
}
Output:
$ java MyPriorityQueue a dddd cc cc cc zz zz zz zz zz The cat in the hat