Top-N 泛型工具类

一、代码实现

通过封装 PriorityQueue 实现,PriorityQueue 本质上是完全二叉树实现的小根堆(相对来说,如果比较器反向比较则是大根堆)。

java 复制代码
public class TopNUtil<E extends Comparable<E>> {
    private final PriorityQueue<E> priorityQueue;
    private final int n;

    /**
     * 构造 Top-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;
    }

    /**
     * 向 Top-N 中插入元素
     */
    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);
    }

    /**
     * 将 Top-N 转为从大到小排序的 List
     */
    public List<E> toSortedArrayList() {
        List<E> tempList = new ArrayList<>(priorityQueue);
        tempList.sort(Collections.reverseOrder());
        return tempList;
    }
}

二、使用示例

java 复制代码
class TopNUtilTest {

    @Test
    void test() {
        List<CountDTO> list = new ArrayList<>();
        TopNUtil<CountDTO> top = new TopNUtil<>(3);

        // 生成 10 个随机的 CountDTO
        for (int i = 0; i < 10; i++) {
            CountDTO dto = new CountDTO();
            dto.setOrderPriceSum(BigDecimal.valueOf(Math.random() * 100));
            list.add(dto);
        }

        System.out.println("所有的 CountDTO 值:");
        for (CountDTO dto : list) {
            System.out.print(dto.getOrderPriceSum());
            System.out.print(" ");
        }
        System.out.println();

        // 将列表中的元素添加到 TopNUtil
        for (CountDTO dto : list) {
            top.add(dto);
        }

        // 获取 TopNUtil 中的元素列表
        List<CountDTO> topList = top.toSortedArrayList();

        // 确保列表的大小不超过 3
        assertEquals(3, topList.size());

        // 打印 Top 3 元素的 CountDTO 值
        System.out.println("Top 3 CountDTO 值:");
        for (CountDTO dto : topList) {
            System.out.println(dto.getOrderPriceSum());
        }
    }
}
相关推荐
咩咩啃树皮8 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
鱟鲥鳚8 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
大模型码小白10 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
腾渊信息科技公司11 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地12 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
wuqingshun31415912 小时前
TCP超时重传机制是为了解决什么问题?
java
莫逸风14 小时前
【AgentScope 2.0】 0. 学习指南
java·llm·agent·agentscope
z1234567898615 小时前
2026最新两款AI编程工具深度对比实测
java·数据库·ai编程
yaoxin52112315 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
做个文艺程序员16 小时前
Linux第24篇:Java应用监控体系搭建:Prometheus+Grafana可视化运维
java·grafana·prometheus