우선순위 큐 : 객체의 특정값으로 정렬
- 💾 알고리즘/알고리즘 기초
- 2020. 9. 25. 14:41
Student 클래스의 age 나이를 기준으로 나이가 많은, 적은 순으로 우선순위 큐를 사용하는 방법
나이가 많은 순
import java.util.PriorityQueue;
// 우선순위 큐
// 객체의 특정 값을 기준으로 정렬
public class priorityQueu_Test {
public static class Student implements Comparable<Student> {
String name;
int age;
public Student(String name, int age){
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
return this.age <= o.age ? 1 : -1; // 큰 순서로 정렬
}
}
public static void main(String[] args) {
PriorityQueue<Student> priorityQueue = new PriorityQueue<>();
priorityQueue.add(new Student("AA", 20));
priorityQueue.add(new Student("BB", 77));
priorityQueue.add(new Student("CC", 66));
priorityQueue.add(new Student("DD", 7));
priorityQueue.add(new Student("EE", 43));
priorityQueue.add(new Student("FF", 100));
for (Student student : priorityQueue) {
System.out.println(student.name + " , " + student.age);
}
System.out.println("===============");
// 꺼낼때는 poll로 꺼내야 된다.
while(!priorityQueue.isEmpty()){
Student a = priorityQueue.poll();
System.out.println(a.name + " , " + a.age);
//System.out.println(priorityQueue.poll());
}
}
}
결과
FF , 100
EE , 43
BB , 77
DD , 7
AA , 20
CC , 66
===============
FF , 100
BB , 77
CC , 66
EE , 43
AA , 20
DD , 7
나이가 적은 순
public static class Student implements Comparable<Student> {
String name;
int age;
public Student(String name, int age){
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
return this.age <= o.age ? -1 : 1; // 작은 순서부터 정렬
}
}
DD , 7
AA , 20
EE , 43
CC , 66
BB , 77
FF , 100
'💾 알고리즘 > 알고리즘 기초' 카테고리의 다른 글
다익스트라(Dijkstra Algorithm) (0) | 2020.10.16 |
---|---|
부분집합의 합 (0) | 2020.10.06 |
유니온 파인드 (Union-Find) (0) | 2020.09.23 |
우선순위 큐 : priority_queue (최대힙, 최소힙) (0) | 2020.09.15 |
[DP : 동적계획법] 최대연속부분수열 (0) | 2020.06.19 |