This example is more comprehensive and can happen in your program. Here we’ll use PriorityQueue to process users in order of their importance. To calculate priority of users we’ll use lexicographical order of their names.

Here’s sample User class:

package com.farenda.java.util; public class User { private static long userCounter; private long id; private final String name; public User(String name) { this.id = userCounter++; this.name = name; } public long getId() { return id; } public String getName() { return name; } @Override public String toString() { return "User(id:" + id + ", name: " + name + ")"; } }

Now we need a Comparator that will tell us which user should be processed first:

package com.farenda.java.util; import java.util.Comparator; public class NameComparator implements Comparator<User> { @Override public int compare(User u1, User u2) { return u1.getName().compareTo(u2.getName()); } }

We’ve got all the pieces, so let’s process them according to their priorities:

package com.farenda.java.util; import java.util.PriorityQueue; public class PriorityQueueExample { private void processUsers() { PriorityQueue<User> queue = new PriorityQueue<>(new NameComparator()); queue.add(new User("Jon Snow")); queue.add(new User("Cersei")); queue.add(new User("Littlefinger")); queue.add(new User("Daenerys")); while (!queue.isEmpty()) { System.out.printf("Handling: %s%n", queue.remove()); } } }

Notice that we’ve passed the NameComparator to the queue’s constructor to have it for prioritization.

The players are processed in the following order:

Handling: User(id:1, name: Cersei) Handling: User(id:3, name: Daenerys) Handling: User(id:0, name: Jon Snow) Handling: User(id:2, name: Littlefinger)