Class MinMaxPriorityQueue<E>
- java.lang.Object
-
- java.util.AbstractCollection<E>
-
- java.util.AbstractQueue<E>
-
- com.google.common.collect.MinMaxPriorityQueue<E>
-
- All Implemented Interfaces:
Iterable<E>,Collection<E>,Queue<E>
@Beta @GwtCompatible public final class MinMaxPriorityQueue<E> extends AbstractQueue<E>
A double-ended priority queue, which provides constant-time access to both its least element and its greatest element, as determined by the queue's specified comparator. If no comparator is given at creation time, the natural order of elements is used. If no maximum size is given at creation time, the queue is unbounded.Usage example:
MinMaxPriorityQueue<User> users = MinMaxPriorityQueue.orderedBy(userComparator) .maximumSize(1000) .create();As a
Queueit functions exactly as aPriorityQueue: its head element -- the implicit target of the methodspeek(),poll()andAbstractQueue.remove()-- is defined as the least element in the queue according to the queue's comparator. But unlike a regular priority queue, the methodspeekLast(),pollLast()andremoveLast()are also provided, to act on the greatest element in the queue instead.A min-max priority queue can be configured with a maximum size. If so, each time the size of the queue exceeds that value, the queue automatically removes its greatest element according to its comparator (which might be the element that was just added). This is different from conventional bounded queues, which either block or reject new elements when full.
This implementation is based on the min-max heap developed by Atkinson, et al. Unlike many other double-ended priority queues, it stores elements in a single array, as compact as the traditional heap data structure used in
PriorityQueue.This class is not thread-safe, and does not accept null elements.
Performance notes:
- If you only access one end of the queue, and do use a maximum size, this class will perform
significantly worse than a
PriorityQueuewith manual eviction above the maximum size. In many casesOrdering.leastOf(java.lang.Iterable<E>, int)may work for your use case with significantly improved (and asymptotically superior) performance. - The retrieval operations
peek(),peekFirst(),peekLast(),AbstractQueue.element(), andsizeare constant-time. - The enqueuing and dequeuing operations (
offer(E),add(E), and all the forms ofpoll()andAbstractQueue.remove()) run inO(log n) time. - The
AbstractCollection.remove(Object)andAbstractCollection.contains(java.lang.Object)operations require linear (O(n)) time. - If you only access one end of the queue, and don't use a maximum size, this class is
functionally equivalent to
PriorityQueue, but significantly slower.
- Since:
- 8.0
- Author:
- Sverre Sundsdal, Torbjorn Gannholm
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classMinMaxPriorityQueue.Builder<B>The builder class used in creation of min-max priority queues.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanadd(E element)Adds the given element to this queue.booleanaddAll(Collection<? extends E> newElements)Adds all of the elements in the specified collection to this queue.voidclear()Removes all of the elements from this queue.Comparator<? super E>comparator()Returns the comparator used to order the elements in this queue.static <E extends Comparable<E>>
MinMaxPriorityQueue<E>create()Creates a new min-max priority queue with default settings: natural order, no maximum size, no initial contents, and an initial expected size of 11.static <E extends Comparable<E>>
MinMaxPriorityQueue<E>create(Iterable<? extends E> initialContents)Creates a new min-max priority queue using natural order, no maximum size, and initially containing the given elements.static MinMaxPriorityQueue.Builder<Comparable>expectedSize(int expectedSize)Creates and returns a new builder, configured to buildMinMaxPriorityQueueinstances sized appropriately to holdexpectedSizeelements.Iterator<E>iterator()Returns an iterator over the elements contained in this collection, in no particular order.static MinMaxPriorityQueue.Builder<Comparable>maximumSize(int maximumSize)Creates and returns a new builder, configured to buildMinMaxPriorityQueueinstances that are limited tomaximumSizeelements.booleanoffer(E element)Adds the given element to this queue.static <B> MinMaxPriorityQueue.Builder<B>orderedBy(Comparator<B> comparator)Creates and returns a new builder, configured to buildMinMaxPriorityQueueinstances that usecomparatorto determine the least and greatest elements.Epeek()Retrieves, but does not remove, the head of this queue, or returnsnullif this queue is empty.EpeekFirst()Retrieves, but does not remove, the least element of this queue, or returnsnullif the queue is empty.EpeekLast()Retrieves, but does not remove, the greatest element of this queue, or returnsnullif the queue is empty.Epoll()Retrieves and removes the head of this queue, or returnsnullif this queue is empty.EpollFirst()Removes and returns the least element of this queue, or returnsnullif the queue is empty.EpollLast()Removes and returns the greatest element of this queue, or returnsnullif the queue is empty.EremoveFirst()Removes and returns the least element of this queue.EremoveLast()Removes and returns the greatest element of this queue.intsize()Returns the number of elements in this collection.Object[]toArray()Returns an array containing all of the elements in this collection.-
Methods inherited from class java.util.AbstractQueue
element, remove
-
Methods inherited from class java.util.AbstractCollection
contains, containsAll, isEmpty, remove, removeAll, retainAll, toArray, toString
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface java.util.Collection
contains, containsAll, equals, hashCode, isEmpty, parallelStream, remove, removeAll, removeIf, retainAll, spliterator, stream, toArray, toArray
-
-
-
-
Method Detail
-
create
public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create()
Creates a new min-max priority queue with default settings: natural order, no maximum size, no initial contents, and an initial expected size of 11.
-
create
public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create(Iterable<? extends E> initialContents)
Creates a new min-max priority queue using natural order, no maximum size, and initially containing the given elements.
-
orderedBy
public static <B> MinMaxPriorityQueue.Builder<B> orderedBy(Comparator<B> comparator)
Creates and returns a new builder, configured to buildMinMaxPriorityQueueinstances that usecomparatorto determine the least and greatest elements.
-
expectedSize
public static MinMaxPriorityQueue.Builder<Comparable> expectedSize(int expectedSize)
Creates and returns a new builder, configured to buildMinMaxPriorityQueueinstances sized appropriately to holdexpectedSizeelements.
-
maximumSize
public static MinMaxPriorityQueue.Builder<Comparable> maximumSize(int maximumSize)
Creates and returns a new builder, configured to buildMinMaxPriorityQueueinstances that are limited tomaximumSizeelements. Each time a queue grows beyond this bound, it immediately removes its greatest element (according to its comparator), which might be the element that was just added.
-
size
public int size()
Description copied from interface:java.util.CollectionReturns the number of elements in this collection. If this collection contains more thanInteger.MAX_VALUEelements, returnsInteger.MAX_VALUE.- Specified by:
sizein interfaceCollection<E>- Specified by:
sizein classAbstractCollection<E>- Returns:
- the number of elements in this collection
-
add
@CanIgnoreReturnValue public boolean add(E element)
Adds the given element to this queue. If this queue has a maximum size, after addingelementthe queue will automatically evict its greatest element (according to its comparator), which may beelementitself.- Specified by:
addin interfaceCollection<E>- Specified by:
addin interfaceQueue<E>- Overrides:
addin classAbstractQueue<E>- Parameters:
element- the element to add- Returns:
truealways
-
addAll
@CanIgnoreReturnValue public boolean addAll(Collection<? extends E> newElements)
Description copied from class:java.util.AbstractQueueAdds all of the elements in the specified collection to this queue. Attempts to addAll of a queue to itself result inIllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.This implementation iterates over the specified collection, and adds each element returned by the iterator to this queue, in turn. A runtime exception encountered while trying to add an element (including, in particular, a
nullelement) may result in only some of the elements having been successfully added when the associated exception is thrown.- Specified by:
addAllin interfaceCollection<E>- Overrides:
addAllin classAbstractQueue<E>- Parameters:
newElements- collection containing elements to be added to this queue- Returns:
trueif this queue changed as a result of the call- See Also:
AbstractQueue.add(Object)
-
offer
@CanIgnoreReturnValue public boolean offer(E element)
Adds the given element to this queue. If this queue has a maximum size, after addingelementthe queue will automatically evict its greatest element (according to its comparator), which may beelementitself.- Parameters:
element- the element to add- Returns:
trueif the element was added to this queue, elsefalse
-
poll
@CanIgnoreReturnValue @CheckForNull public E poll()
Description copied from interface:java.util.QueueRetrieves and removes the head of this queue, or returnsnullif this queue is empty.- Returns:
- the head of this queue, or
nullif this queue is empty
-
peek
@CheckForNull public E peek()
Description copied from interface:java.util.QueueRetrieves, but does not remove, the head of this queue, or returnsnullif this queue is empty.- Returns:
- the head of this queue, or
nullif this queue is empty
-
pollFirst
@CanIgnoreReturnValue @CheckForNull public E pollFirst()
Removes and returns the least element of this queue, or returnsnullif the queue is empty.
-
removeFirst
@CanIgnoreReturnValue public E removeFirst()
Removes and returns the least element of this queue.- Throws:
NoSuchElementException- if the queue is empty
-
peekFirst
@CheckForNull public E peekFirst()
Retrieves, but does not remove, the least element of this queue, or returnsnullif the queue is empty.
-
pollLast
@CanIgnoreReturnValue @CheckForNull public E pollLast()
Removes and returns the greatest element of this queue, or returnsnullif the queue is empty.
-
removeLast
@CanIgnoreReturnValue public E removeLast()
Removes and returns the greatest element of this queue.- Throws:
NoSuchElementException- if the queue is empty
-
peekLast
@CheckForNull public E peekLast()
Retrieves, but does not remove, the greatest element of this queue, or returnsnullif the queue is empty.
-
iterator
public Iterator<E> iterator()
Returns an iterator over the elements contained in this collection, in no particular order.The iterator is fail-fast: If the MinMaxPriorityQueue is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will generally throw a
ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw
ConcurrentModificationExceptionon a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.- Specified by:
iteratorin interfaceCollection<E>- Specified by:
iteratorin interfaceIterable<E>- Specified by:
iteratorin classAbstractCollection<E>- Returns:
- an iterator over the elements contained in this collection
-
clear
public void clear()
Description copied from class:java.util.AbstractQueueRemoves all of the elements from this queue. The queue will be empty after this call returns.This implementation repeatedly invokes
polluntil it returnsnull.- Specified by:
clearin interfaceCollection<E>- Overrides:
clearin classAbstractQueue<E>
-
toArray
public Object[] toArray()
Description copied from class:java.util.AbstractCollectionReturns an array containing all of the elements in this collection. If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array's runtime component type isObject.The returned array will be "safe" in that no references to it are maintained by this collection. (In other words, this method must allocate a new array even if this collection is backed by an array). The caller is thus free to modify the returned array.
- Specified by:
toArrayin interfaceCollection<E>- Overrides:
toArrayin classAbstractCollection<E>- Returns:
- an array, whose runtime component
type is
Object, containing all of the elements in this collection
-
comparator
public Comparator<? super E> comparator()
Returns the comparator used to order the elements in this queue. Obeys the general contract ofPriorityQueue.comparator, but returnsOrdering.natural()instead ofnullto indicate natural ordering.
-
-