new PriorityQueue
new PriorityQueue<[type]>()
//오름차순
PriorityQueue<Integer> pq = new PriorityQueue<>();
//내림차순
PriorityQueue<Integer> pqHightest = new PriorityQueue<>(Collections.reverseOrder());
- add
- offer
add(E element)
offer(E element)
pq.add(3);
pq.add(1);
pq.offer(2); //pq: [1, 3, 2]
- poll
- remove
- removeIf
- removeAll
- clear
poll()
remove()
pq.poll();
pq.remove();
removeIf(Predicate<? super E> filter)
//pq: [1, 2, 3, 4, 5]
pq.removeIf(n -> (n % 2 == 0)); //pq: [1, 3, 5]
remove(E element)
removeAll(Collection<?>)
//pq1: [1, 2, 3, 4, 5]
//pq2: [1, 3, 5]
pq1.removeAll(pq2); //p1: [2, 4]
pq1.remove(9); //false
- peek
- iterator
peek()
int i = pq.peek();
iterator()
//pq: [1, 3, 2]
Iterator<Integer> iter = pq.iterator();
while(iter.hasNext()) {
Integer i = iter.next();
System.out.print(i + " ");
}
출력
1 3 2
- size
- toArray
- contains
size()
int size = pq.size()
toArray()
for(Object i : pq.toArray()) {
System.out.println(i);
}
출력
1 3 2
특정 기준으로 정렬하고 싶거나 큐에 저장된 객체의 어떤 속성으로 정렬하고 싶을 때 다음을 이용한다.
1. implements Comparable
2. Comparator 생성
예제 클래스
public class People {
String name;
int age;
int height;
}
public class People implements Comparable<People>{
String name;
int age;
int height;
@Override
public int compareTo(People o) {
// 키로 오름차순 정렬
// 현재 객체가 o보다 작으면 -1, 크면 1 반환
// 동일하면 0 반환
return (this.height > o.height ? 1 : -1);
}
}
PriorityQueue<People> pq = new PriorityQueue<>(new Comparator<People>() {
@Override
public int compare(People o1, People o2) {
return o1.height > o2.height ? 1 : -1;
}
});