PriorityQueue优先级队列数据实体需要实现排序【Comparator | Comparable】
- 队列数据类
@Data
public static class A implements Comparable<A>{
private Integer a=Integer.MAX_VALUE;
@Override
public int compareTo(@NotNull A o) {
return a.compareTo(o.getA());
}
}
- 队列初始化
PriorityQueue<A> pq=new PriorityQueue<>();
Stream.iterate(0,e->e++).limit(10).forEach(e->{
A a=new A();
a.setA(RandomUtil.randomInt(10,1000));
pq.add(a);
});
- 骚操作
尝试迭代数据输出【期望迭代输出数据为有序数据】
pq.forEach(e->{
System.out.println(e.getA());
});
迭代结果【普通迭代非有序】
//结果
23
281
584
546
395
888
884
678
933
496
有效姿势【使用poll】
Stream.iterate(0,e->e++).limit(10).forEach(e->{
System.out.println(pq.poll().getA());;
});
//结果
100
154
191
355
476
581
619
791
794
872
结果总要经过努力尝试后才会有,换个角度换个姿势,既能收获知识点也能获得乐趣