从优先队列中删除特定元素的代码部分不需要翻译。

huangapple go评论59阅读模式
英文:

Remove sepecific elememt from Priority Queue of Pair

问题

以下是翻译好的部分:

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

这是优先队列的定义,可以看到元素是根据值而不是键进行排序,键-值对中的值。

现在我想要删除一个特定的元素(不在队列顶部),使用键作为搜索因素。
假设队列有以下元素:

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

我想要删除键为(3)的元素(3,4)。

预期删除后的输出应该是:

[[2, 1], [1, 5]]
英文:
PriorityQueue&lt;Pair&lt;Integer, Integer&gt;&gt; p = new PriorityQueue&lt;&gt;((a,b)-&gt;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&lt;&gt;(2,1));
p.add(new Pair&lt;&gt;(3,4));
p.add(new Pair&lt;&gt;(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]]

答案1

得分: 5

你可以使用 removeIf

p.removeIf(x -> x.getKey() == 3);
// 移除所有键等于3的元素
英文:

You could use removeIf.

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

huangapple
  • 本文由 发表于 2023年7月18日 12:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定