Sample Code
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 Order Queue with ******" ); the while (! Queue.isEmpty ()) { System.out.println (queue.poll ()); } // use the comparator generated when the queue does not use class Comparable interface queue generateQueue = ((X, Y) -> { int Delta = y.getAge () - x.getAge (); return Delta <0 -1: (? == 0 0 Delta:? 1 ); }); System.out.println ( "****** ****** Comparator the Read Queue with the Order" ); the while (! queue.isEmpty ()) { System.out.println (queue.poll ()); } } / ** * @param comparator priority queue elemental comparator for comparing * If not null, the elemental parity comparator, comparator precedence * if null, use of the method elements compareTo (Comparable interface need to inherit ) * @return * / Private static PriorityQueue <the User> generateQueue (Comparator <the User> Comparator) { PriorityQueue <the User> Queue = new new PriorityQueue <> (Comparator); for ( int I = 30; I> 20 is; i-- ) { queue.add ( new new the 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 + "]"; } } }
operation result
******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]