PriorityQueue

드코미·2025년 9월 12일

Java에서 PriorityQueue 사용법을 정리한 글입니다.


Java PriorityQueue 사용법

PriorityQueue는 Java에서 우선순위 큐(priority queue)를 구현한 클래스입니다.
일반적인 큐(FIFO)와 달리, 요소가 들어온 순서와 상관없이 우선순위가 높은 요소가 먼저 나옵니다.
내부적으로는 힙(Heap) 자료구조를 기반으로 동작합니다.


1. 기본 선언

import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        // 기본은 최소 힙 (작은 값이 먼저 나온다)
        PriorityQueue<Integer> pq = new PriorityQueue<>();

        // 값 추가
        pq.add(5);
        pq.add(1);
        pq.add(3);

        // 가장 작은 값 출력
        System.out.println(pq.peek()); // 1

        // 가장 작은 값 꺼내기 (poll은 제거하면서 꺼냄)
        System.out.println(pq.poll()); // 1
        System.out.println(pq.poll()); // 3
        System.out.println(pq.poll()); // 5
    }
}

2. 최대 힙 만들기

PriorityQueue는 기본적으로 오름차순(최소 힙) 입니다.
만약 내림차순(최대 힙) 으로 쓰고 싶다면 Comparator를 지정해야 합니다.

import java.util.PriorityQueue;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        // 최대 힙 (큰 값이 먼저 나온다)
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

        maxHeap.add(5);
        maxHeap.add(1);
        maxHeap.add(3);

        System.out.println(maxHeap.poll()); // 5
        System.out.println(maxHeap.poll()); // 3
        System.out.println(maxHeap.poll()); // 1
    }
}

3. 객체(클래스)에서 사용하기

객체를 PriorityQueue에 넣으려면 우선순위 기준을 정해야 합니다.
방법은 2가지가 있습니다.

(1) Comparable 인터페이스 구현

import java.util.PriorityQueue;

class Person implements Comparable<Person> {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 나이가 적을수록 우선순위가 높다
    @Override
    public int compareTo(Person other) {
        return this.age - other.age;
    }
}

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Person> pq = new PriorityQueue<>();

        pq.add(new Person("Alice", 30));
        pq.add(new Person("Bob", 20));
        pq.add(new Person("Charlie", 25));

        while (!pq.isEmpty()) {
            Person p = pq.poll();
            System.out.println(p.name + " (" + p.age + ")");
        }
        // 출력: Bob (20), Charlie (25), Alice (30)
    }
}

(2) Comparator 사용

import java.util.PriorityQueue;
import java.util.Comparator;

class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        // 나이가 많은 순서대로 우선순위
        PriorityQueue<Person> pq = new PriorityQueue<>(Comparator.comparingInt(p -> -p.age));

        pq.add(new Person("Alice", 30));
        pq.add(new Person("Bob", 20));
        pq.add(new Person("Charlie", 25));

        while (!pq.isEmpty()) {
            Person p = pq.poll();
            System.out.println(p.name + " (" + p.age + ")");
        }
        // 출력: Alice (30), Charlie (25), Bob (20)
    }
}

4. 주요 메서드 정리

메서드설명
add(E e)요소 추가 (실패 시 예외 발생)
offer(E e)요소 추가 (실패 시 false 반환)
peek()가장 우선순위 높은 요소 확인 (제거 안 함)
poll()가장 우선순위 높은 요소 꺼내고 제거
isEmpty()큐가 비었는지 확인
size()큐에 들어 있는 요소 개수

5. 정리

  • PriorityQueue힙 기반 우선순위 큐
  • 기본은 최소 힙, Collections.reverseOrder()최대 힙 가능
  • 객체는 Comparable 구현 또는 Comparator 지정으로 우선순위 정의

👉 실전 코딩테스트에서 그리디, 다익스트라, 시뮬레이션(대기열 문제) 등에 많이 쓰이는 자료구조입니다.

profile
할 수 있다!!!

0개의 댓글