Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java PriorityQueue by example

farenda 2016-05-03 0

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:

  • Check out Java Collections Tutorial for more useful tips for Java Collections!
Share with the World!
Categories Java Tags java, java-collections
Previous: Java ListResourceBundle example
Next: Java Split String in various ways

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored