BoundedPriorityQueue

BoundedPriorityQueue

Introduction

Let’s say I have a user table that is hashed by username to different database instances. To find the top 5 most popular users, what would I do? My approach would be:

  1. Find the top 5 most popular users on each database instance
  2. Sort these 5 records on each database instance by popularity, and then retrieve the top 5 records

This process may seem simple, but it requires writing a lot of code on the application server. It needs to query N lists, combine them into a new list, sort it, and then retrieve the top 5. This process not only involves cumbersome code but also wastes a lot of space with multiple lists.

Therefore, the BoundedPriorityQueue comes into existence.

First, let’s take a look at the Demo:

/**
 * Demo of Bounded Priority Queue
 * @author Looly
 *
 */
public class BoundedPriorityQueueDemo {
  public static void main(String[] args) {
    // Initialize the queue with a capacity of 5 (can only accommodate 5 elements), and use the default comparator for elements of type integer. The queue will be sorted in ascending order internally.
    BoundedPriorityQueue<Integer> queue = new BoundedPriorityQueue<Integer>(5);
    // Initialize the queue with a custom comparator
    queue = new BoundedPriorityQueue<>(5, new Comparator<Integer>(){
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      }
    });
    // Define 6 elements. When elements are added to the queue, they will be sorted in ascending order. When the 6th element is added, the element at the end of the queue (the largest element) will be discarded.
    int[] array = new int[]{5,7,9,2,3,8};
    for (int i : array) {
      queue.offer(i);
    }
    // The queue can be converted to a List哦~~
    ArrayList<Integer> list = queue.toList();
    System.out.println(queue);
  }
}

The principle is very simple. After setting the capacity of the queue, all data is added or offered into the queue (both methods are the same), and the top 5 records will be obtained.