Skip to content

Instantly share code, notes, and snippets.

@iamcrypticcoder
Created September 23, 2021 16:19
Show Gist options
  • Save iamcrypticcoder/46526aa0225e5590075445bd2959cad3 to your computer and use it in GitHub Desktop.
Save iamcrypticcoder/46526aa0225e5590075445bd2959cad3 to your computer and use it in GitHub Desktop.
PriorityQueueDemoJava
import java.util.AbstractMap;
import java.util.Comparator;
import java.util.Map;
import java.util.PriorityQueue;
public class PriorityQueueDemo {
public static void main(String[] args) {
priorityQueueDemo1();
priorityQueueDemo2();
priorityQueueDemo3();
}
static void priorityQueueDemo1() {
PriorityQueue<Integer> pq1 = new PriorityQueue<>();
PriorityQueue<Integer> pq2 = new PriorityQueue<>(Comparator.reverseOrder());
int[] arr = new int[] {10, 4, 2, 7, 1, 9, 3};
for (int x : arr) {
pq1.offer(x);
pq2.offer(x);
}
while (!pq1.isEmpty()) {
System.out.println(pq1.poll() + " " + pq2.poll());
}
System.out.println();
}
static void priorityQueueDemo2() {
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((p1, p2) -> {
if (p1.getKey() == p2.getKey())
return p1.getValue() - p2.getValue();
return p1.getKey() - p2.getKey();
});
int[] arr1 = new int[] {4, 3, 2, 7, 0, 4};
int[] arr2 = new int[] {3, 6, 1, 9, 3, 10};
for (int i = 0; i < arr1.length; i++)
pq.offer(Pair.of(arr1[i], arr2[i]));
while (!pq.isEmpty()) {
Map.Entry<Integer, Integer> p = pq.poll();
System.out.println(p.getKey() + " " + p.getValue());
}
System.out.println();
}
static void priorityQueueDemo3() {
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
(p1, p2) -> {
if (p1.getValue() == p2.getValue())
return p1.getKey().compareTo(p2.getKey());
return p2.getValue().compareTo(p1.getValue());
});
String[] strArr = new String[] {"bob", "leonardo", "alex", "david", "monika"};
int[] intArr = new int[] {2, 1, 2, 4, 2};
for (int i = 0; i < strArr.length; i++) {
Map.Entry<String, Integer> p = Main.Pair.of(strArr[i], intArr[i]);
pq.offer(p);
}
while (!pq.isEmpty()) {
Map.Entry<String, Integer> p = pq.poll();
System.out.println(p.getKey() + " " + p.getValue());
}
System.out.println();
}
static class Pair {
public static <T, U> Map.Entry<T, U> of(T first, U second) {
return new AbstractMap.SimpleEntry<>(first, second);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment