우선순위 큐
정의
가장 높은 우선순위를 가진 항목에 접근, 삭제, 임의의 우선순위를 가진 항목의 삽입을 지원하는 자료구조
사용법
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()
를 사용하면 역순으로 정의
'개발 기초 > 언어' 카테고리의 다른 글
[JavaScript] 함수와 일급 객체 (1) | 2025.02.03 |
---|---|
[JavaScript] 생성자 함수에 의한 객체 생성 (1) | 2025.01.22 |
[JavaScript] 프로퍼티 어트리뷰트 (0) | 2025.01.08 |
[JavaScript] let, const 키워드와 블록 레벨 스코프 (2) | 2025.01.04 |
[JavaScript] 전역변수의 문제점 (0) | 2025.01.02 |