Java priority queue PriorityQueue

1. Overview of PriorityQueue

Java PriorityQueue implements the Queue interface and does not allow null elements

  • It is implemented through a heap, specifically: a small top heap implemented through a complete binary tree (the weight of any non-leaf node is not greater than the weight of its left and right child nodes), which means that an array can be used as a PriorityQueue The underlying implementation, the initial size of the array is 11; it can also be represented by a complete binary tree.
  • The role of the priority queue is to ensure that the elements taken out each time are the least weighted elements in the queue. The size relationship is involved here. The size of an element can be judged by the natural ordering of the element itself, or by the comparison passed in during construction (Comparator, similar to a C++ functor).

2. Summary of common methods

public boolean add(E e); //在队尾插入元素,插入失败时抛出异常,并调整堆结构
public boolean offer(E e); //在队尾插入元素,插入失败时抛出false,并调整堆结构

public E remove(); //获取队头元素并删除,并返回,失败时前者抛出异常,再调整堆结构
public E poll(); //获取队头元素并删除,并返回,失败时前者抛出null,再调整堆结构

public E element(); //返回队头元素(不删除),失败时前者抛出异常
public E peek()//返回队头元素(不删除),失败时前者抛出null

public boolean isEmpty(); //判断队列是否为空
public int size(); //获取队列中元素个数
public void clear(); //清空队列
public boolean contains(Object o); //判断队列中是否包含指定元素(从队头到队尾遍历)
public Iterator<E> iterator(); //迭代器

3. Heap structure adjustment

After each insertion or deletion of an element, the queue is adjusted so that the queue always forms a min-heap (or a max-heap).

The specific adjustments are as follows:

  • After inserting elements, adjust the heap from the bottom of the heap to the top of the heap;
  • After deleting elements, copy the tail element to the head and adjust the heap from the top of the heap to the bottom of the heap.

Small root heap structure adjustment:

  • After inserting (the add() and offer() methods) the element, adjust the heap upwards:
  • After removing (the remove() and poll() methods) elements, adjust the heap downwards:

4. Specific use

1. Implement descending order

Method 1, lambda expression

PriorityQueue<Integer> queue = new PriorityQueue<>(
    (o1, o2) -> o2 - o1
);

Method 2. Rewrite the compare method

PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
    
    
    @Override
    public int compare(Integer o1, Integer o2) {
    
    
        return o2 - o1;
    }
});

2. Implement custom sorting

Example 1. Sort in descending order by the third character of the string

PriorityQueue<String> queue = new PriorityQueue<>(
    (o1, o2) -> o2.charAt(2) - o1.charAt(2)
);

Example 2: Customize a class People, first sort by name, then by age, then by height

PriorityQueue<People> queue = new PriorityQueue<>(
    (o1, o2) -> {
    
    
        if (o1.getName().compareTo(o2.getName()) > 0) {
    
    
            return 1;
        } else if (o1.getName().compareTo(o2.getName()) < 0) {
    
    
            return -1;
        } else {
    
    
            if (o1.getAge() > o2.getAge()) {
    
    
                return 1;
            } else if (o1.getAge() < o2.getAge()) {
    
    
                return -1;
            } else {
    
    
                if (o1.getHeight() - o2.getHeight() > 0) {
    
    
                    return 1;
                } else if (o1.getHeight() - o2.getHeight() < 0) {
    
    
                    return -1;
                } else {
    
    
                    return 0;
                }
            }
        }
    }
);

Guess you like

Origin blog.csdn.net/twi_twi/article/details/130020469