threads
PriorityQueue example
In this example we shall show you how to use a PriorityQueue. To use a PriorityQueue one should perform the following steps:
- Create a new Comparator for Integer objects, that is a comparison function, which imposes a total ordering on some collection of objects.
- Override the
compare(Integer i, Integer j)
method of Comparator in order to make a specified comparison. - Create a new PriorityQueue with a specified initial capacity, that orders its elements according to the specified comparator.
- Use
offer(Integer e)
API method of PriorityQueue to insert an element to the PriorityQueue for comparison. - Use
poll()
API method of PriorityQueue to get the head of the queue,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; public class PriorityQueueExample { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(20, new Comparator<Integer>() { @Override public int compare(Integer i, Integer j) { int result = i % 2 - j % 2; if (result == 0) { result = i - j; } return result; } }); for (int i = 0; i < 20; i++) { pq.offer(20 - i); } for (int i = 0; i < 20; i++) { System.out.println(pq.poll()); } } }
Output:
2
4
6
8
10
12
14
16
18
20
1
3
5
7
9
11
13
15
17
19
This was an example of how to use a PriorityQueue in Java.