Usage example:
MinMaxPriorityQueue<User> users = MinMaxPriorityQueue.orderedBy(userComparator)
.maximumSize(1000)
.create();
As a Queue it functions exactly as a PriorityQueue: its head element -- the
implicit target of the methods peek(), poll() and remove() -- is
defined as the least element in the queue according to the queue's comparator. But unlike
a regular priority queue, the methods peekLast, pollLast and removeLast 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:
PriorityQueue with manual eviction above the maximum
size. In many cases Ordering#leastOf may work for your use case with significantly
improved (and asymptotically superior) performance.
peek, peekFirst, peekLast, element, and size are constant-time.
offer, add, and all the forms of
poll and remove()) run in O(log n) time.
remove(Object) and contains operations require linear (O(n))
time.
PriorityQueue, but significantly slower.
| Modifier and Type | Class and Description |
|---|---|
| public static class | MinMaxPriorityQueue.
the upper bound on the eventual type that can be produced by this builder (for
example, a B>Builder<Number> can produce a Queue<Number> or Queue<Integer> but not a Queue<Object>).The builder class used in creation of min-max priority queues. |
| pack-priv class | MinMaxPriorityQueue.
Each instance of MinMaxPriorityQueue encapsulates two instances of Heap: a min-heap and a max-heap. |
| pack-priv static class | |
| private class | MinMaxPriorityQueue.
Iterates the elements of the queue in no particular order. |
| Modifier and Type | Field and Description |
|---|---|
| private static final int | |
| private static final int | |
| private final MinMaxPriorityQueue | |
| pack-priv final int | |
| private final MinMaxPriorityQueue | |
| private int | |
| private static final int | |
| private @Nullable Object[] | |
| private int |
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| public boolean | Returns: true alwaysthe element to add element)Overrides java. Implements java. |
| public boolean | addAll(Collection<? extends E>
collection containing elements to be added to this queue newElements)Overrides java. Implements java. |
| private int | |
| pack-priv int | |
| private static int | capAtMaximumSize(int queueSize, int maximumSize)
There's no reason for the queueSize to ever be more than maxSize + 1 |
| public void | clear()
Overrides java. Implements java. |
| public Comparator | |
| public static <E extends Comparable | 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. |
| public static <E extends Comparable | |
| pack-priv E | |
| public static MinMaxPriorityQueue. | expectedSize(int expectedSize)
Creates and returns a new builder, configured to build |
| private MinMaxPriorityQueue. | |
| private int | |
| private void | |
| private MinMaxPriorityQueue | |
| pack-priv static int | |
| pack-priv static boolean | |
| pack-priv boolean | |
| public Iterator | Returns: an iterator over the elements contained in this collectionImplements abstract java. Implements java. |
| public static MinMaxPriorityQueue. | maximumSize(int maximumSize)
Creates and returns a new builder, configured to build |
| public boolean | offer(E
the element to add element)Implements java. |
| public static <B> MinMaxPriorityQueue. | orderedBy(Comparator<B> comparator)
Creates and returns a new builder, configured to build |
| public E | peek()
Implements java. null if this queue is empty.
|
| public E | peekFirst()
Retrieves, but does not remove, the least element of this queue, or returns |
| public E | peekLast()
Retrieves, but does not remove, the greatest element of this queue, or returns |
| public E | poll()
Implements java. null if this queue is empty.
|
| public E | pollFirst()
Removes and returns the least element of this queue, or returns |
| public E | pollLast()
Removes and returns the greatest element of this queue, or returns |
| private E | |
| pack-priv MinMaxPriorityQueue. | |
| public E | |
| public E | |
| public int | size()
Implements abstract java. Implements java. |
| public Object[] | toArray()
Overrides java. Implements java. |
| DEFAULT_CAPACITY | back to summary |
|---|---|
| private static final int DEFAULT_CAPACITY | |
| EVEN_POWERS_OF_TWO | back to summary |
|---|---|
| private static final int EVEN_POWERS_OF_TWO | |
| maxHeap | back to summary |
|---|---|
| private final MinMaxPriorityQueue<E>. | |
| maximumSize | back to summary |
|---|---|
| pack-priv final int maximumSize
| |
| minHeap | back to summary |
|---|---|
| private final MinMaxPriorityQueue<E>. | |
| modCount | back to summary |
|---|---|
| private int modCount | |
| ODD_POWERS_OF_TWO | back to summary |
|---|---|
| private static final int ODD_POWERS_OF_TWO | |
| queue | back to summary |
|---|---|
| private @Nullable Object[] queue | |
| size | back to summary |
|---|---|
| private int size | |
| MinMaxPriorityQueue | back to summary |
|---|---|
| private MinMaxPriorityQueue(MinMaxPriorityQueue. | |
| add | back to summary |
|---|---|
| public boolean add(E element) Overrides java. Implements java. Adds the given element to this queue. If this queue has a maximum size, after adding
| |
| addAll | back to summary |
|---|---|
| public boolean addAll(Collection<? extends E> newElements) Overrides java. Implements java. Doc from java. Adds all of the elements in the specified collection to this
queue. Attempts to addAll of a queue to itself result in
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
| |
| calculateNewCapacity | back to summary |
|---|---|
| private int calculateNewCapacity() Returns ~2x the old capacity if small; ~1.5x otherwise. | |
| capacity | back to summary |
|---|---|
pack-priv int capacity()
| |
| capAtMaximumSize | back to summary |
|---|---|
| private static int capAtMaximumSize(int queueSize, int maximumSize) There's no reason for the queueSize to ever be more than maxSize + 1 | |
| clear | back to summary |
|---|---|
| public void clear() Overrides java. Implements java. Doc from java. Removes all of the elements from this queue. The queue will be empty after this call returns. This implementation repeatedly invokes
| |
| comparator | back to summary |
|---|---|
| public Comparator Returns the comparator used to order the elements in this queue. Obeys the general contract of
| |
| create | back to summary |
|---|---|
| public static <E extends Comparable 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 | back to summary |
|---|---|
| public static <E extends Comparable Creates a new min-max priority queue using natural order, no maximum size, and initially containing the given elements. | |
| elementData | back to summary |
|---|---|
pack-priv E elementData(int index)
| |
| expectedSize | back to summary |
|---|---|
| public static MinMaxPriorityQueue. Creates and returns a new builder, configured to build
| |
| fillHole | back to summary |
|---|---|
private MinMaxPriorityQueue.
| |
| getMaxElementIndex | back to summary |
|---|---|
| private int getMaxElementIndex() Returns the index of the max element. | |
| growIfNeeded | back to summary |
|---|---|
| private void growIfNeeded() | |
| heapForIndex | back to summary |
|---|---|
| private MinMaxPriorityQueue | |
| initialQueueSize | back to summary |
|---|---|
pack-priv static int initialQueueSize(int configuredExpectedSize, int maximumSize, Iterable<?> initialContents)
| |
| isEvenLevel | back to summary |
|---|---|
pack-priv static boolean isEvenLevel(int index)
| |
| isIntact | back to summary |
|---|---|
| pack-priv boolean isIntact() Returns TODO(kevinb): move to the test class?
| |
| iterator | back to summary |
|---|---|
| public Iterator Implements abstract java. Implements java. 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 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 | |
| maximumSize | back to summary |
|---|---|
| public static MinMaxPriorityQueue. Creates and returns a new builder, configured to build
| |
| offer | back to summary |
|---|---|
| public boolean offer(E element) Implements java. Adds the given element to this queue. If this queue has a maximum size, after adding
| |
| orderedBy | back to summary |
|---|---|
| public static <B> MinMaxPriorityQueue. Creates and returns a new builder, configured to build | |
| peek | back to summary |
|---|---|
| public E peek() Implements java. Doc from java. Retrieves, but does not remove, the head of this queue,
or returns
| |
| peekFirst | back to summary |
|---|---|
| public E peekFirst() Retrieves, but does not remove, the least element of this queue, or returns
| |
| peekLast | back to summary |
|---|---|
| public E peekLast() Retrieves, but does not remove, the greatest element of this queue, or returns
| |
| poll | back to summary |
|---|---|
| public E poll() Implements java. Doc from java. Retrieves and removes the head of this queue,
or returns
| |
| pollFirst | back to summary |
|---|---|
| public E pollFirst() Removes and returns the least element of this queue, or returns
| |
| pollLast | back to summary |
|---|---|
| public E pollLast() Removes and returns the greatest element of this queue, or returns
| |
| removeAndGet | back to summary |
|---|---|
| private E removeAndGet(int index) Removes and returns the value at | |
| removeAt | back to summary |
|---|---|
| pack-priv MinMaxPriorityQueue. Removes the element at position Normally this method leaves the elements at up to Occasionally, in order to maintain the heap invariant, it must swap a later element of the
list with one before
| |
| removeFirst | back to summary |
|---|---|
| public E removeFirst() Removes and returns the least element of this queue.
| |
| removeLast | back to summary |
|---|---|
| public E removeLast() Removes and returns the greatest element of this queue.
| |
| size | back to summary |
|---|---|
| public int size() Implements abstract java. Implements java. Doc from java. Returns the number of elements in this collection. If this collection
contains more than
| |
| toArray | back to summary |
|---|---|
| public Object[] toArray() Overrides java. Implements java. Doc from java. Returns 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 is 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.
| |
Builder<Number> can produce a Queue<Number> or Queue<Integer> but not a Queue<Object>).
MinMaxPriorityQueue#orderedBy(Comparator), MinMaxPriorityQueue#expectedSize(int) or MinMaxPriorityQueue#maximumSize(int).
| Modifier and Type | Field and Description |
|---|---|
| private final Comparator | |
| private int | |
| private int | |
| private static final int |
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| public <T extends B> MinMaxPriorityQueue | create()
Builds a new min-max priority queue using the previously specified options, and having no initial contents. |
| public <T extends B> MinMaxPriorityQueue | |
| public MinMaxPriorityQueue. | expectedSize(int expectedSize)
Configures this builder to build min-max priority queues with an initial expected size of
|
| public MinMaxPriorityQueue. | maximumSize(int maximumSize)
Configures this builder to build |
| private <T extends B> Ordering |
| comparator | back to summary |
|---|---|
| private final Comparator<B> comparator | |
| expectedSize | back to summary |
|---|---|
| private int expectedSize | |
| maximumSize | back to summary |
|---|---|
| private int maximumSize | |
| UNSET_EXPECTED_SIZE | back to summary |
|---|---|
| private static final int UNSET_EXPECTED_SIZE | |
| Builder | back to summary |
|---|---|
| private Builder(Comparator<B> comparator) | |
| create | back to summary |
|---|---|
| public <T extends B> MinMaxPriorityQueue Builds a new min-max priority queue using the previously specified options, and having no initial contents. | |
| create | back to summary |
|---|---|
| public <T extends B> MinMaxPriorityQueue Builds a new min-max priority queue using the previously specified options, and having the given initial elements. | |
| expectedSize | back to summary |
|---|---|
| public MinMaxPriorityQueue. Configures this builder to build min-max priority queues with an initial expected size of
| |
| maximumSize | back to summary |
|---|---|
| public MinMaxPriorityQueue. Configures this builder to build
| |
| ordering | back to summary |
|---|---|
private <T extends B> Ordering
| |
| Modifier and Type | Field and Description |
|---|---|
| pack-priv final Ordering | |
| pack-priv MinMaxPriorityQueue |
| Modifier and Type | Method and Description |
|---|---|
| pack-priv void | |
| pack-priv int | bubbleUpAlternatingLevels(int index, E x)
Bubbles a value from |
| pack-priv int | |
| pack-priv int | crossOver(int index, E x)
Crosses an element over to the opposite heap by moving it one level down (or up if there are no elements below it). |
| pack-priv int | crossOverUp(int index, E x)
Moves an element one level up from a min level to a max level (or vice versa). |
| pack-priv int | Returns: the position of the new hole (where the lowest grandchild moved from, that had no grandchild to replace it)Fills the hole at |
| pack-priv int | findMin(int index, int len)
Returns the index of minimum value between |
| pack-priv int | |
| pack-priv int | |
| private int | |
| private int | |
| private int | |
| private int | |
| pack-priv int | swapWithConceptuallyLastElement(E actualLastElement)
Swap |
| pack-priv MinMaxPriorityQueue. | tryCrossOverAndBubbleUp(int removeIndex, int vacated, E toTrickle)
Tries to move |
| private boolean |
| ordering | back to summary |
|---|---|
| pack-priv final Ordering<E> ordering | |
| otherHeap | back to summary |
|---|---|
pack-priv MinMaxPriorityQueue<E>.
| |
| Heap | back to summary |
|---|---|
| pack-priv Heap(Ordering<E> ordering) | |
| bubbleUp | back to summary |
|---|---|
| pack-priv void bubbleUp(int index, E x) Bubbles a value from | |
| bubbleUpAlternatingLevels | back to summary |
|---|---|
| pack-priv int bubbleUpAlternatingLevels(int index, E x) Bubbles a value from
| |
| compareElements | back to summary |
|---|---|
| pack-priv int compareElements(int a, int b) | |
| crossOver | back to summary |
|---|---|
| pack-priv int crossOver(int index, E x) Crosses an element over to the opposite heap by moving it one level down (or up if there are no elements below it). Returns the new position of the element. | |
| crossOverUp | back to summary |
|---|---|
| pack-priv int crossOverUp(int index, E x) Moves an element one level up from a min level to a max level (or vice versa). Returns the new position of the element. | |
| fillHoleAt | back to summary |
|---|---|
| pack-priv int fillHoleAt(int index) Fills the hole at
| |
| findMin | back to summary |
|---|---|
| pack-priv int findMin(int index, int len) Returns the index of minimum value between | |
| findMinChild | back to summary |
|---|---|
| pack-priv int findMinChild(int index) Returns the minimum child or | |
| findMinGrandChild | back to summary |
|---|---|
| pack-priv int findMinGrandChild(int index) Returns the minimum grand child or -1 if no grand child exists. | |
| getGrandparentIndex | back to summary |
|---|---|
| private int getGrandparentIndex(int i) | |
| getLeftChildIndex | back to summary |
|---|---|
| private int getLeftChildIndex(int i) | |
| getParentIndex | back to summary |
|---|---|
| private int getParentIndex(int i) | |
| getRightChildIndex | back to summary |
|---|---|
| private int getRightChildIndex(int i) | |
| swapWithConceptuallyLastElement | back to summary |
|---|---|
| pack-priv int swapWithConceptuallyLastElement(E actualLastElement) Swap Since the last element of the array is actually in the middle of the sorted structure, a childless aunt node could be smaller, which would corrupt the invariant if this element becomes the new parent of the aunt node. In that case, we first switch the last element with its aunt node, before returning. | |
| tryCrossOverAndBubbleUp | back to summary |
|---|---|
| pack-priv MinMaxPriorityQueue. Tries to move
| |
| verifyIndex | back to summary |
|---|---|
| private boolean verifyIndex(int i) | |
| Modifier and Type | Field and Description |
|---|---|
| pack-priv final E | |
| pack-priv final E |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| replaced | back to summary |
|---|---|
| pack-priv final E replaced | |
| toTrickle | back to summary |
|---|---|
| pack-priv final E toTrickle | |
| MoveDesc | back to summary |
|---|---|
| pack-priv MoveDesc(E toTrickle, E replaced) | |
If the underlying queue is modified during iteration an exception will be thrown.
| Modifier and Type | Field and Description |
|---|---|
| private boolean | |
| private int | |
| private int | |
| private Queue | |
| private E | |
| private int | |
| private List |
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| private void | |
| private boolean | foundAndRemovedExactReference(Iterable<E> elements, E target)
Returns true if an exact reference (==) was found and removed from the supplied iterable. |
| public boolean | |
| public E | |
| private void | nextNotInSkipMe(int c)
Advances nextCursor to the index of the first element after |
| public void | remove()
Overrides default java. |
| private boolean |
| canRemove | back to summary |
|---|---|
| private boolean canRemove | |
| cursor | back to summary |
|---|---|
| private int cursor | |
| expectedModCount | back to summary |
|---|---|
| private int expectedModCount | |
| forgetMeNot | back to summary |
|---|---|
| private Queue<E> forgetMeNot
| |
| lastFromForgetMeNot | back to summary |
|---|---|
| private E lastFromForgetMeNot
| |
| nextCursor | back to summary |
|---|---|
| private int nextCursor | |
| skipMe | back to summary |
|---|---|
| private List<E> skipMe
| |
| QueueIterator | back to summary |
|---|---|
| private QueueIterator() | |
| checkModCount | back to summary |
|---|---|
| private void checkModCount() | |
| foundAndRemovedExactReference | back to summary |
|---|---|
| private boolean foundAndRemovedExactReference(Iterable<E> elements, E target) Returns true if an exact reference (==) was found and removed from the supplied iterable. | |
| hasNext | back to summary |
|---|---|
| public boolean hasNext() Implements java. Doc from java. Returns
| |
| next | back to summary |
|---|---|
| public E next() Implements java. Doc from java. Returns the next element in the iteration.
| |
| nextNotInSkipMe | back to summary |
|---|---|
| private void nextNotInSkipMe(int c) Advances nextCursor to the index of the first element after | |
| remove | back to summary |
|---|---|
| public void remove() Overrides default java. Doc from java. Removes from the underlying collection the last element returned
by this iterator (optional operation). This method can be called
only once per call to The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy.
The behavior of an iterator is unspecified if this method is called
after a call to the
| |
| removeExact | back to summary |
|---|---|
| private boolean removeExact(Object target) Removes only this exact instance, not others that are equals() | |