如何在Java中使用Lambda初始化存储大顶堆的HashMap
Java中初始化存储大顶堆的HashMap
先明确几个正确的基础写法:
- 存储小顶堆的HashMap初始化:
Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();
- 单独用Lambda初始化大顶堆:
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
你尝试的Map<Integer, PriorityQueue<Integer>((a, b) -> b - a)> map = new HashMap<>();写法是错误的,因为泛型声明只定义类型,不能包含实例的初始化逻辑——Lambda是用来创建Comparator实例作为PriorityQueue的构造参数,不属于泛型类型的一部分。
正确实现方式
方式1:初始化Map后手动放入大顶堆实例
在需要向Map中添加元素时,创建带Lambda比较器的大顶堆并放入:
Map<Integer, PriorityQueue<Integer>> map = new HashMap<>(); // 向map中放入key为1、对应大顶堆的条目 map.put(1, new PriorityQueue<>((a, b) -> b - a));
方式2:使用computeIfAbsent自动创建大顶堆
如果希望在访问不存在的key时自动创建对应的大顶堆,可以用computeIfAbsent方法,它会在key不存在时执行Lambda创建实例:
Map<Integer, PriorityQueue<Integer>> map = new HashMap<>(); // 当key=2不存在时,自动创建大顶堆并放入map,同时返回该堆 PriorityQueue<Integer> targetPq = map.computeIfAbsent(2, k -> new PriorityQueue<>((a, b) -> b - a));
方式3:批量初始化大顶堆条目
如果需要一次性创建多个带大顶堆的条目,可以结合循环实现:
Map<Integer, PriorityQueue<Integer>> map = new HashMap<>(); // 初始化key从1到3的大顶堆条目 for (int i = 1; i <= 3; i++) { map.put(i, new PriorityQueue<>((a, b) -> b - a)); }
内容的提问来源于stack exchange,提问作者mmast
相关产品推荐
相关产品推荐

