개발 기초/언어

[Java] Priority Queue 클래스 사용자 정의 방법

숩니따 2025. 1. 22. 18:26

우선순위 큐

정의

가장 높은 우선순위를 가진 항목에 접근, 삭제, 임의의 우선순위를 가진 항목의 삽입을 지원하는 자료구조

사용법

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

PriorityQueue<자료형> 변수명 = new PriorityQueue<>();

기존 정렬

오름차순

PriorityQueue<자료형> 변수명 = new PriorityQueue<>();

내림차순

PriorityQueue<자료형> 변수명 = new PriorityQueue<>(Collections.reverseOrder());

사용자 정의

람다식

compare 메서드를 구현하지 않고 자바8 이상에서 편리하게 사용 가능

PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> x - y);

Comparator 인터페이스 활용

람다식보다 좀 더 복잡한 로직을 정의할 수 있으며 익명 클래스를 통해 구현

PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
    @Override
    public int compare(Integer x, Integer y) {
        return x - y;
    }
});

Comparable 인터페이스 활용

객체 자체에서 비교 방법을 정의하는 방법으로 객체 내부에 비교 로직 포함

public class MyObject implements Comparable<MyObject> {
    private int value;

    @Override
    public int compareTo(MyObject other) {
        return Integer.compare(this.value, other.value);
    }
}

PriorityQueue<MyObject> pq = new PriorityQueue<>();

Comparator의 메서드 사용

Comparator의 헬퍼 메서드를 사용하여 특정 필드에 기반한 비교자를 쉽게 생성할 수 있으며 데이터 타입에 따라 다른 함수 제공

PriorityQueue<MyObject> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o.getValue()));  // 람다식 표현식
PriorityQueue<MyObject> pq = new PriorityQueue<>(Comparator.comparingInt(MyObject::getValue))  // 메서드 참조
  • Integer → Comparator.comparingInt
  • Long → Comparator.comparingLong
  • Double → Comparator.comparingDouble
  • String → Comparator.comparing

참고로 .reversed()를 사용하면 역순으로 정의