Close

Java Collections - PriorityQueue.remove() Examples

Java Collections Java Java API 


Class:

java.util.PriorityQueue

java.lang.Objectjava.lang.Objectjava.util.AbstractCollectionjava.util.AbstractCollectionjava.util.CollectionCollectionjava.util.AbstractQueuejava.util.AbstractQueuejava.util.QueueQueuejava.util.PriorityQueuejava.util.PriorityQueuejava.io.SerializableSerializableLogicBig

Method:

public boolean remove(Object o)

Removes a single instance of the specified element from this queue, if it is present.


public E remove()

Retrieves and removes the head of this queue. This method differs from PriorityQueue.poll() only in that it throws java.util.NoSuchElementException if this queue is empty.

This method is inherited from AbstractQueue.

This method and the last method are not overloaded because of different return types.


Examples


package com.logicbig.example.priorityqueue;

import java.util.PriorityQueue;

public class RemoveExample {

public static void main(String... args) {
PriorityQueue<String> pq = new PriorityQueue<>();
pq.offer("one");
pq.offer("two");
System.out.println(pq);
boolean b = pq.remove("one");
System.out.println(b);
System.out.println(pq);
boolean b2 = pq.remove("one");
System.out.println(b2);
}
}

Output

[one, two]
true
[two]
false




package com.logicbig.example.priorityqueue;

import java.util.PriorityQueue;

public class RemoveExample2 {

public static void main(String... args) {
PriorityQueue<String> pq = new PriorityQueue<>();
pq.add("one");
pq.add("two");
pq.add("one");
System.out.println(pq);
pq.remove("one");
System.out.println(pq);
}
}

Output

[one, two, one]
[one, two]




E remove() example:

package com.logicbig.example.priorityqueue;

import java.util.NoSuchElementException;
import java.util.PriorityQueue;

public class RemoveExample3 {

public static void main(String... args) {
PriorityQueue<String> pq = new PriorityQueue<>();
pq.add("c");
pq.add("a");
pq.add("b");
System.out.println(pq);

while (true) {
try {
String element = pq.remove();
System.out.println(element);
} catch (NoSuchElementException e) {
break;
}
}
}
}

Output

[a, c, b]
a
b
c




See Also