示例代码
package com.example.base.concurrent; import java.util.Comparator; import java.util.PriorityQueue; public class MyPriorityQueue { public static void main(String[] args) { foo(); } private static void foo() { PriorityQueue<User> queue = generateQueue(null); System.out.println("******read queue without order******"); for (User user : queue) { System.out.println(user); } //queue = generateQueue(); System.out.println("******read queue with order******"); while(!queue.isEmpty()) { System.out.println(queue.poll()); } //产生队列时使用comparator,不使用类的Comparable接口 queue = generateQueue((x,y) ->{ int delta = y.getAge() - x.getAge(); return delta < 0 ? -1 : (delta == 0 ? 0 : 1); }); System.out.println("******read queue with order comparator******"); while(!queue.isEmpty()) { System.out.println(queue.poll()); } } /** * @param comparator 优先级队列中进行元素比较的比较器 * 如果不为null,则使用comparator进行元素比价,优先使用comparator * 如果为null,则使用元素的compareTo方法(需要继承Comparable接口) * @return */ private static PriorityQueue<User> generateQueue(Comparator<User> comparator) { PriorityQueue<User> queue = new PriorityQueue<>(comparator); for (int i = 30; i > 20; i--) { queue.add(new User(i, "gc"+i)); } return queue; } private static class User implements Comparable<User> { private int age; private String name; public User(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } @Override public int compareTo(User o) { int delta = this.getAge() - o.getAge(); return delta < 0 ? -1 : (delta == 0 ? 0 : 1); } @Override public String toString() { return "User [age=" + age + ", name=" + name + "]"; } } }
运行结果
******read queue without order****** User [age=21, name=gc21] User [age=22, name=gc22] User [age=25, name=gc25] User [age=24, name=gc24] User [age=23, name=gc23] User [age=29, name=gc29] User [age=26, name=gc26] User [age=30, name=gc30] User [age=27, name=gc27] User [age=28, name=gc28] ******read queue with order****** User [age=21, name=gc21] User [age=22, name=gc22] User [age=23, name=gc23] User [age=24, name=gc24] User [age=25, name=gc25] User [age=26, name=gc26] User [age=27, name=gc27] User [age=28, name=gc28] User [age=29, name=gc29] User [age=30, name=gc30] ******read queue with order2****** User [age=30, name=gc30] User [age=29, name=gc29] User [age=28, name=gc28] User [age=27, name=gc27] User [age=26, name=gc26] User [age=25, name=gc25] User [age=24, name=gc24] User [age=23, name=gc23] User [age=22, name=gc22] User [age=21, name=gc21]
原文地址:https://www.cnblogs.com/gc65/p/11183787.html
时间: 2024-10-20 10:58:33