思路

  1. 大->小 or 小->大排列

實作

測試方法

import java.util.Comparator; // 比較器 
import java.util.PriorityQueue; // priority queue 

public class Priority_Queue2 {
    public static void main(String[] args) {
        // default
        Integer[] nums = new Integer[]{4,3,1,5,2};
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int i = 0 ; i < nums.length; i++) {
            pq.add(nums[i]);
        }

        while (true) {
            if (pq.size() == 0) break; // 跑完無內容

            Integer num_min = pq.poll(); // 取出最小值 by default
            System.out.print(num_min + " ");

情境

依照等待時間排序 小 -> 大

static class Person {
    Integer age;
    Integer peepee_wait_time;

    public Person(Integer age, Integer peepee_wait_time) {
        this.age = age;
        this.peepee_wait_time = peepee_wait_time;
    }
}

// 實作比較器邏輯
static class MyComp implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        return p1.peepee_wait_time.compareTo(p2.peepee_wait_time); // low -> high
    }
}

public static void main(String[] args) {
    // custom
    // 放入人的資料
    Person[] ppl = new Person[] {
            new Person(19, 60)
            ,new Person(28, 45)
            ,new Person(48, 32)
            ,new Person(60, 19)
            ,new Person(33, 200)
    };

    // 配置 priority queue
    // https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#PriorityQueue()
    // PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
    // 依照比較器 compare 排序
    PriorityQueue<Person> pq_ppl = new PriorityQueue<>(ppl.length, new MyComp());
    for (int i = 0 ; i < ppl.length; i++) {
        pq_ppl.add(ppl[i]); // 依序加入
    }

    System.out.print("\npeepee wait time: ");
    while (true) {
        if (pq_ppl.size() == 0) break; // 無內容時break

        Person p = pq_ppl.poll();
        System.out.print(p.peepee_wait_time + " ");

    }

    System.out.println();
}