第一个例子:
创建小根堆(堆顶元素最小):
PriorityQueue queue=new PriorityQueue();
//向堆里面添加元素
queue.add(0);
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
queue.add(6);
//输出堆中全部元素
while(queue.isEmpty()==false)
{
System.out.println(queue.remove());
}
//输出:0,1,2,3,4,5,6,即小根堆每次弹出当前堆里面最小的元素
创建大根堆
PriorityQueue queue=new PriorityQueue(
{
public int compare(Integer a,Integer b)
{
//这里如果是return a-b就是生成一个小根堆,return b-a就是生成一个大根堆
return b-a;
}
}
);
//向堆里面添加元素
queue.add(0);
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
queue.add(6);
//输出堆中全部元素
while(queue.isEmpty()==false)
{
System.out.println(queue.remove());
}
//输出6,5,4,3,2,1,0即大根堆每次弹出当前堆里面最大的元素
更简洁的创建大根堆的方式:
PriorityQueue<Integer> queue=new PriorityQueue( (a,b)->(b-a) )
第二个例子:
人为设置堆内元素的比较依据:
比较依据:堆内元素对应的哈希值
PriorityQueue<Integer> queue=new PriorityQueue<Integer>((a,b)->map.get(a)-map.get(b));
比较依据:堆内元素(是结点)对应的结点值
PriorityQueue<ListNode> queue=new PriorityQueue<ListNode>((a,b)->(a.val-b.val));
第三个例子:
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(-1);
arrayList.add(3);
arrayList.add(3);
arrayList.add(-5);
arrayList.add(7);
arrayList.add(4);
arrayList.add(-9);
arrayList.add(-7);
System.out.println("原始数组:");
System.out.println(arrayList);
// void reverse(List list):反转
Collections.reverse(arrayList);
System.out.println("Collections.reverse(arrayList):");
System.out.println(arrayList);
// void sort(List list),按自然排序的升序排序
Collections.sort(arrayList);
System.out.println("Collections.sort(arrayList):");
System.out.println(arrayList);
// 定制排序的用法
Collections.sort(arrayList, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
System.out.println("定制排序后:");
System.out.println(arrayList);
输出:
原始数组:
[-1, 3, 3, -5, 7, 4, -9, -7]
Collections.reverse(arrayList):
[-7, -9, 4, 7, -5, 3, 3, -1]
Collections.sort(arrayList):
[-9, -7, -5, -1, 3, 3, 4, 7]
定制排序后:
[7, 4, 3, 3, -1, -5, -7, -9]
第四个例子:
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/**
* T重写compareTo方法实现按年龄来排序
*/
@Override
public int compareTo(Person o) {
if (this.age > o.getAge()) {
return 1;
}
if (this.age < o.getAge()) {
return -1;
}
return 0;
}
}
public static void main(String[] args) {
TreeMap<Person, String> pdata = new TreeMap<Person, String>();
pdata.put(new Person("张三", 30), "zhangsan");
pdata.put(new Person("李四", 20), "lisi");
pdata.put(new Person("王五", 10), "wangwu");
pdata.put(new Person("小红", 5), "xiaohong");
// 得到key的值的同时得到key所对应的值
Set<Person> keys = pdata.keySet();
for (Person key : keys) {
System.out.println(key.getAge() + "-" + key.getName());
}
}