Java Programming Tutorials

Java programming tutorials with many code examples!

Java PriorityQueue by example

Java PriorityQueue by example

In this tutorial we’re going to show how to use PriorityQueue to process queue elements in order of importance, not insertion.

Sort numbers using PriorityQueue

The following example shows how PriorityQueue can leverage natural ordering of Comparable elements in order to sort them:

package com.farenda.java.util;

import java.util.PriorityQueue;
import java.util.Random;

public class PriorityQueueExample {

    private void sortNumbers() {
        PriorityQueue<Integer> queue = new PriorityQueue<>();

        // Generate sample numbers:
        Random rand = new Random();
        for (int i = 0; i < 10; ++i) {
            queue.add(rand.nextInt(100));
        }

        while (!queue.isEmpty()) {
            System.out.printf("%d,", queue.remove());
        }
        System.out.println();
    }
}

Sample output of the above program:

3,13,21,46,48,49,55,65,67,92,

As you can see the numbers are sorted ascendingly, because PriorityQueue is using natural ordering of Comparable and integers are comparable.

PriorityQueue with custom Comparator

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)

PriorityQueue and concurrency

Keep in mind that PriorityQueue is not thread-safe and should not be used concurrently by multiple threads. For concurrent processing use PriorityBlockingQueue.

References:

Share with the World!