一、代码实现
public class TopNUtil<E extends Comparable<E>> {
private final PriorityQueue<E> priorityQueue;
private final int n;
public TopNUtil(int size) {
if (size <= 0) {
throw new IllegalArgumentException("Top-N size must be a positive number");
}
this.priorityQueue = new PriorityQueue<>(size);
this.n = size;
}
public void add(E e) {
if (priorityQueue.size() < n) {
priorityQueue.add(e);
return;
}
E head = priorityQueue.peek();
if (head != null && e.compareTo(head) <= 0) {
return;
}
priorityQueue.poll();
priorityQueue.add(e);
}
public List<E> toSortedArrayList() {
List<E> tempList = new ArrayList<>(priorityQueue);
tempList.sort(Collections.reverseOrder());
return tempList;
}
}
二、使用示例
class TopNUtilTest {
@Test
void test() {
List<HerbOrderPriceCountDTO> list = new ArrayList<>();
TopNUtil<HerbOrderPriceCountDTO> top = new TopNUtil<>(3);
for (int i = 0; i < 10; i++) {
HerbOrderPriceCountDTO dto = new HerbOrderPriceCountDTO();
dto.setOrderPriceSum(BigDecimal.valueOf(Math.random() * 100));
list.add(dto);
}
System.out.println("所有的 orderFlow 值:");
for (HerbOrderPriceCountDTO dto : list) {
System.out.print(dto.getOrderPriceSum());
System.out.print(" ");
}
System.out.println();
for (HerbOrderPriceCountDTO dto : list) {
top.add(dto);
}
List<HerbOrderPriceCountDTO> topList = top.toSortedArrayList();
assertEquals(3, topList.size());
System.out.println("Top 3 orderFlow 值:");
for (HerbOrderPriceCountDTO dto : topList) {
System.out.println(dto.getOrderPriceSum());
}
}
}