Unfortunately iteration via queue doesn't maintain priority queue invariant, otherwise solution would be fully declarative:

PriorityQueue<Map.Entry<Integer, Long>> q =

new PriorityQueue<>((o1, o2) -> Long.compare(o2.getValue(), o1.getValue()));

```
q.addAll(Arrays.stream(nums)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet());
List<Integer> result = new ArrayList<>();
while (k>0) {
result.add(q.remove().getKey());
k--;
}
return result;
```