Priority Queue : In Java Priority Queue is a queue which keeps its elements sorted as per their natural order( example in ascending orders for Integer, alphabetical a-z for alphabets) or using a custom Comparator at the time of creation you can custom sort it.
It has most method similar to a queue add, clear, poll, peek
As priority queue have to compare elements to keep in order so elements must be comparable otherwise, it will throw ClassCastException .
As null can not be compared so you are not allowed to insert null too
A program to sort priority queue using Lambda function in Java
class PriorityQueueLambdaJava{
public List<Integer> KFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int j: nums) {
map.put(j, map.getOrDefault(j, 0) + 1);
}
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((p1, p2) -> p1.getValue() - p2.getValue());
map.entrySet().forEach(e -> {
pq.offer(e);
if (pq.size() > k) {
pq.poll();
}
});
return pq.stream().map(p -> p.getKey()).collect(Collectors.toList());
}
}Post is inspired form Oracle documents for java
Comments
Post a Comment