Java中的优先队列PriorityQueue的使用及相关方法

简单使用

PriorityQueue<Integer> p = new PriorityQueue<>();

优先级队列从队头取元素,从队尾添加元素。 默认情况下,队列中的数据是升序排序。

PriorityQueue<Integer> p = new PriorityQueue<>();
p.offer(5);
p.offer(1);
p.offer(3);
p.offer(6);
p.offer(8);

while(!p.isEmpty()) {
          
   
	System.out.println(p.poll());
}

运行结果:

1
3
5
6
8

方法

和队列的方法基本一样

自定义排序规则

以下代码改变排序规则,从大到小:

PriorityQueue<Integer> queue=new PriorityQueue<>((o1,o2)->o2-o1);

PriorityQueue<Integer> queue= new PriorityQueue<>(Comparator.reverseOrder());

根据HashMap的value值对HashMap的键值对排序

public static void main(String[] args) {
          
   
	HashMap<Integer, Integer> map = new HashMap<>();
	map.put(1, 2);
	map.put(3, 4);
	map.put(5, 6);
	
	Set<Map.Entry<Integer, Integer>> entries = map.entrySet();//获取键值对
	
	//自定义优先队列的排序规则,队列内存放的数据类型是键值对
	//o1,o2都是键值对这样的对象
	PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> {
          
   
		return o1.getValue() - o2.getValue();//根据值升序排序
	});
	
	for (Map.Entry<Integer, Integer> entry : entries) {
          
   
		queue.offer(entry);//将键值对放到优先队列中
    }
	while(!queue.isEmpty()) {
          
   
		System.out.println(queue.poll().getValue());
	}
}

运行结果:

2
4
6
经验分享 程序员 微信小程序 职场和发展