// how to implement self-defined priorityqueue comparator in java /** * @author lautturi.com * Java example: custom Comparator for PriorityQueue in java */ import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; class stringLenComparator implements Comparator<String> { public int compare(String s1, String s2) { if (s1.length() > s2.length()) return -1; else if (s1.length() < s2.length()) return 1; else return 0; } } public class Lautturi { public static void main(String[] args) throws IOException { PriorityQueue<String> prq = new PriorityQueue<>(new stringLenComparator()); // insert values to the queue prq.add("python"); prq.add("hello"); prq.add("js"); prq.add("php"); prq.add("perl"); prq.add("world"); //print the PriorityQueue while (!prq.isEmpty()) { System.out.println(prq.poll()+" "); } } }
output:
python hello world perl php js