반응형
큐는 작업하고 싶은 순서대로 정렬할 때 사용된다
또한,Collection
의 인터페이스를 구현하여,Collection
메서드를 사용가능하다.
📚 PriorityQueue
기본적으로 정렬되서 큐를 생성한다
🚀 구현 코드
public static void main(String[] args) {
Queue<String> queue = new PriorityQueue<>();
queue.addAll(List.of("안녕","하세요","반갑습니다"));
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue.poll());
}
✅ 결과
위와같이, 들어간 순서에 상관없이 사전순으로 자료가 나오게 되어있다.
우선순위를 바꾸려면
우선순위를 바꾸기 위해서는
Comparator
인터페이스의 구현체를PriorityQueue
의생성자에 넘겨줘야한다.
🚀 구현코드
//StringLengthComparator.java
class StringLengthComparator implements Comparator<String>{
@Override
public int compare(String value1, String value2) {
return Integer.compare(value1.length(),value2.length());
}
}
//QueueRunner.java
public static void main(String[] args) {
//아래와 같이 Comparator를 주입한다.
Queue<String> queue = new PriorityQueue<>(new StringLengthComparator());
queue.addAll(List.of("안녕","하세요","반갑습니다"));
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue.poll());
}
✅ 결과
위와 같이 문자열의 길이에 따른 순서로 반환되는 것을 볼 수 있다.
반응형
'JAVA > 컬렉션과 자료구조' 카테고리의 다른 글
14. Set인터페이스 실습 (0) | 2024.01.01 |
---|---|
13. 트리 (1) | 2024.01.01 |
12. 해싱 (1) | 2024.01.01 |
10. 컬렉션의 정렬 (0) | 2024.01.01 |
9. 컬렉션 (0) | 2024.01.01 |