队列是java高级开发中常用开发技术,普通队列弹出顺序默认FIFO(先进先出)
优先级队列可以默认或指定算法,自动约束数据弹出顺序,本文记录jdk自带非线程安全优先级队列PriorityQueue。
PriorityBlockingQueue 优先级队列线程安全。
import java.util.PriorityQueue;
import java.util.Queue;
public class MainTest {
public static void main(String[] args) {
Queue<Integer> p = new PriorityQueue<>();
p.offer(1);
p.offer(2);
p.offer(5);
p.offer(4);
p.offer(3);
System.out.println(p.poll());
System.out.println(p.poll());
System.out.println(p.poll());
System.out.println(p.poll());
System.out.println(p.poll());
}
}
//输出 1 、2、3、4、5
import java.util.PriorityQueue;
import java.util.Queue;
public class MainTest {
public static void main(String[] args) {
Queue<Integer> p = new PriorityQueue<>(Collections.reverseOrder());
p.offer(1);
p.offer(2);
p.offer(5);
p.offer(4);
p.offer(3);
System.out.println(p.poll());
System.out.println(p.poll());
System.out.println(p.poll());
System.out.println(p.poll());
System.out.println(p.poll());
}
}
//输出 5、4、3、2、1
import java.util.List;
/**
* 学生类
*/
public class Student {
//姓名
public String name;
//各科分数
public List<Integer> score;
public Student (String name ,List<Integer> score){
this.name=name;
this.score=score;
}
public Student (){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Integer> getScore() {
return score;
}
public void setScore(List<Integer> score) {
this.score = score;
}
public int getAvg(){
return score.stream().reduce(0, Integer::sum)/score.size();
}
@Override
public String toString() {
return "name:"+name+",score:"+score+",平均分:"+getAvg();
}
}
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Arrays;
public class MainTest {
public static void main(String[] args) {
Student student1 = new Student("小明", Arrays.asList(77, 78, 90));
Student student2 = new Student("小王", Arrays.asList(88, 65, 81));
Student student3 = new Student("小红", Arrays.asList(92, 78, 90));
Student student4 = new Student("小李", Arrays.asList(44, 98, 88));
Queue<Student> q = new PriorityQueue<>((a, b) -> {
//计算每个学生分数的平均分,降序排序(即平均分越高优先级越高,越先出队列)
return b.getAvg() - a.getAvg();
});
q.offer(student1);
q.offer(student2);
q.offer(student3);
q.offer(student4);
System.out.println(q.poll().toString());
System.out.println(q.poll().toString());
System.out.println(q.poll().toString());
System.out.println(q.poll().toString());
}
}
name:小红,score:[92, 78, 90],平均分:86
name:小明,score:[77, 78, 90],平均分:81
name:小王,score:[88, 65, 81],平均分:78
name:小李,score:[44, 98, 88],平均分:76