Search code examples
javapriority-queue

Remove sepecific elememt from Priority Queue of Pair


PriorityQueue<Pair<Integer, Integer>> p = new PriorityQueue<>((a,b)->a.getValue()-b.getValue());

This is how the Priority Queue is defined, in which you can see that the elements are sorted according to the value and not the key, in the key-value pair. Now I want to remove a specific element (not on top of queue), using the key as a seach factor. Say the Queue has elements ->

p.add(new Pair<>(2,1));
p.add(new Pair<>(3,4));
p.add(new Pair<>(1,5);

I want to delete the element (3,4), using the key (3);

The expected Output after Deletion should be -> [[2,1], [1,5]]


Solution

  • You could use removeIf.

    p.removeIf(x -> x.getKey() == 3);
    // removes all elements with key equal to 3