우선순위 큐 : 객체의 특정값으로 정렬

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

댓글

Designed by JB FACTORY