Using a comparator class with priority queue.
import java.util.Comparator;
import java.util.PriorityQueue;
public class UsingComparator {
public static void main(String [] args) {
PriorityQueue<String> stringsByLength = new PriorityQueue<String>(new CompareByLength());
stringsByLength.add("hello");
stringsByLength.add("hi");
stringsByLength.add("greetings");
stringsByLength.add("bye");
while(!stringsByLength.isEmpty()) {
System.out.println(stringsByLength.poll());
}
}
}
class CompareByLength implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
CSci 2101
course web site.