001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.errorprone.annotations.CanIgnoreReturnValue;
021import com.google.errorprone.annotations.CompatibleWith;
022import java.util.Collection;
023import java.util.Collections;
024import java.util.Iterator;
025import java.util.List;
026import java.util.Set;
027import org.checkerframework.checker.nullness.compatqual.NullableDecl;
028
029/**
030 * A collection that supports order-independent equality, like {@link Set}, but may have duplicate
031 * elements. A multiset is also sometimes called a <i>bag</i>.
032 *
033 * <p>Elements of a multiset that are equal to one another are referred to as <i>occurrences</i> of
034 * the same single element. The total number of occurrences of an element in a multiset is called
035 * the <i>count</i> of that element (the terms "frequency" and "multiplicity" are equivalent, but
036 * not used in this API). Since the count of an element is represented as an {@code int}, a multiset
037 * may never contain more than {@link Integer#MAX_VALUE} occurrences of any one element.
038 *
039 * <p>{@code Multiset} refines the specifications of several methods from {@code Collection}. It
040 * also defines an additional query operation, {@link #count}, which returns the count of an
041 * element. There are five new bulk-modification operations, for example {@link #add(Object, int)},
042 * to add or remove multiple occurrences of an element at once, or to set the count of an element to
043 * a specific value. These modification operations are optional, but implementations which support
044 * the standard collection operations {@link #add(Object)} or {@link #remove(Object)} are encouraged
045 * to implement the related methods as well. Finally, two collection views are provided: {@link
046 * #elementSet} contains the distinct elements of the multiset "with duplicates collapsed", and
047 * {@link #entrySet} is similar but contains {@link Entry Multiset.Entry} instances, each providing
048 * both a distinct element and the count of that element.
049 *
050 * <p>In addition to these required methods, implementations of {@code Multiset} are expected to
051 * provide two {@code static} creation methods: {@code create()}, returning an empty multiset, and
052 * {@code create(Iterable<? extends E>)}, returning a multiset containing the given initial
053 * elements. This is simply a refinement of {@code Collection}'s constructor recommendations,
054 * reflecting the new developments of Java 5.
055 *
056 * <p>As with other collection types, the modification operations are optional, and should throw
057 * {@link UnsupportedOperationException} when they are not implemented. Most implementations should
058 * support either all add operations or none of them, all removal operations or none of them, and if
059 * and only if all of these are supported, the {@code setCount} methods as well.
060 *
061 * <p>A multiset uses {@link Object#equals} to determine whether two instances should be considered
062 * "the same," <i>unless specified otherwise</i> by the implementation.
063 *
064 * <p>Common implementations include {@link ImmutableMultiset}, {@link HashMultiset}, and {@link
065 * ConcurrentHashMultiset}.
066 *
067 * <p>If your values may be zero, negative, or outside the range of an int, you may wish to use
068 * {@link com.google.common.util.concurrent.AtomicLongMap} instead. Note, however, that unlike
069 * {@code Multiset}, {@code AtomicLongMap} does not automatically remove zeros.
070 *
071 * <p>See the Guava User Guide article on <a href=
072 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multiset"> {@code
073 * Multiset}</a>.
074 *
075 * @author Kevin Bourrillion
076 * @since 2.0
077 */
078@GwtCompatible
079public interface Multiset<E> extends Collection<E> {
080  // Query Operations
081
082  /**
083   * Returns the total number of all occurrences of all elements in this multiset.
084   *
085   * <p><b>Note:</b> this method does not return the number of <i>distinct elements</i> in the
086   * multiset, which is given by {@code entrySet().size()}.
087   */
088  @Override
089  int size();
090
091  /**
092   * Returns the number of occurrences of an element in this multiset (the <i>count</i> of the
093   * element). Note that for an {@link Object#equals}-based multiset, this gives the same result as
094   * {@link Collections#frequency} (which would presumably perform more poorly).
095   *
096   * <p><b>Note:</b> the utility method {@link Iterables#frequency} generalizes this operation; it
097   * correctly delegates to this method when dealing with a multiset, but it can also accept any
098   * other iterable type.
099   *
100   * @param element the element to count occurrences of
101   * @return the number of occurrences of the element in this multiset; possibly zero but never
102   *     negative
103   */
104  int count(@NullableDecl @CompatibleWith("E") Object element);
105
106  // Bulk Operations
107
108  /**
109   * Adds a number of occurrences of an element to this multiset. Note that if {@code occurrences ==
110   * 1}, this method has the identical effect to {@link #add(Object)}. This method is functionally
111   * equivalent (except in the case of overflow) to the call {@code
112   * addAll(Collections.nCopies(element, occurrences))}, which would presumably perform much more
113   * poorly.
114   *
115   * @param element the element to add occurrences of; may be null only if explicitly allowed by the
116   *     implementation
117   * @param occurrences the number of occurrences of the element to add. May be zero, in which case
118   *     no change will be made.
119   * @return the count of the element before the operation; possibly zero
120   * @throws IllegalArgumentException if {@code occurrences} is negative, or if this operation would
121   *     result in more than {@link Integer#MAX_VALUE} occurrences of the element
122   * @throws NullPointerException if {@code element} is null and this implementation does not permit
123   *     null elements. Note that if {@code occurrences} is zero, the implementation may opt to
124   *     return normally.
125   */
126  @CanIgnoreReturnValue
127  int add(@NullableDecl E element, int occurrences);
128
129  /**
130   * Removes a number of occurrences of the specified element from this multiset. If the multiset
131   * contains fewer than this number of occurrences to begin with, all occurrences will be removed.
132   * Note that if {@code occurrences == 1}, this is functionally equivalent to the call {@code
133   * remove(element)}.
134   *
135   * @param element the element to conditionally remove occurrences of
136   * @param occurrences the number of occurrences of the element to remove. May be zero, in which
137   *     case no change will be made.
138   * @return the count of the element before the operation; possibly zero
139   * @throws IllegalArgumentException if {@code occurrences} is negative
140   */
141  @CanIgnoreReturnValue
142  int remove(@NullableDecl @CompatibleWith("E") Object element, int occurrences);
143
144  /**
145   * Adds or removes the necessary occurrences of an element such that the element attains the
146   * desired count.
147   *
148   * @param element the element to add or remove occurrences of; may be null only if explicitly
149   *     allowed by the implementation
150   * @param count the desired count of the element in this multiset
151   * @return the count of the element before the operation; possibly zero
152   * @throws IllegalArgumentException if {@code count} is negative
153   * @throws NullPointerException if {@code element} is null and this implementation does not permit
154   *     null elements. Note that if {@code count} is zero, the implementor may optionally return
155   *     zero instead.
156   */
157  @CanIgnoreReturnValue
158  int setCount(E element, int count);
159
160  /**
161   * Conditionally sets the count of an element to a new value, as described in {@link
162   * #setCount(Object, int)}, provided that the element has the expected current count. If the
163   * current count is not {@code oldCount}, no change is made.
164   *
165   * @param element the element to conditionally set the count of; may be null only if explicitly
166   *     allowed by the implementation
167   * @param oldCount the expected present count of the element in this multiset
168   * @param newCount the desired count of the element in this multiset
169   * @return {@code true} if the condition for modification was met. This implies that the multiset
170   *     was indeed modified, unless {@code oldCount == newCount}.
171   * @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is negative
172   * @throws NullPointerException if {@code element} is null and the implementation does not permit
173   *     null elements. Note that if {@code oldCount} and {@code newCount} are both zero, the
174   *     implementor may optionally return {@code true} instead.
175   */
176  @CanIgnoreReturnValue
177  boolean setCount(E element, int oldCount, int newCount);
178
179  // Views
180
181  /**
182   * Returns the set of distinct elements contained in this multiset. The element set is backed by
183   * the same data as the multiset, so any change to either is immediately reflected in the other.
184   * The order of the elements in the element set is unspecified.
185   *
186   * <p>If the element set supports any removal operations, these necessarily cause <b>all</b>
187   * occurrences of the removed element(s) to be removed from the multiset. Implementations are not
188   * expected to support the add operations, although this is possible.
189   *
190   * <p>A common use for the element set is to find the number of distinct elements in the multiset:
191   * {@code elementSet().size()}.
192   *
193   * @return a view of the set of distinct elements in this multiset
194   */
195  Set<E> elementSet();
196
197  /**
198   * Returns a view of the contents of this multiset, grouped into {@code Multiset.Entry} instances,
199   * each providing an element of the multiset and the count of that element. This set contains
200   * exactly one entry for each distinct element in the multiset (thus it always has the same size
201   * as the {@link #elementSet}). The order of the elements in the element set is unspecified.
202   *
203   * <p>The entry set is backed by the same data as the multiset, so any change to either is
204   * immediately reflected in the other. However, multiset changes may or may not be reflected in
205   * any {@code Entry} instances already retrieved from the entry set (this is
206   * implementation-dependent). Furthermore, implementations are not required to support
207   * modifications to the entry set at all, and the {@code Entry} instances themselves don't even
208   * have methods for modification. See the specific implementation class for more details on how
209   * its entry set handles modifications.
210   *
211   * @return a set of entries representing the data of this multiset
212   */
213  Set<Entry<E>> entrySet();
214
215  /**
216   * An unmodifiable element-count pair for a multiset. The {@link Multiset#entrySet} method returns
217   * a view of the multiset whose elements are of this class. A multiset implementation may return
218   * Entry instances that are either live "read-through" views to the Multiset, or immutable
219   * snapshots. Note that this type is unrelated to the similarly-named type {@code Map.Entry}.
220   *
221   * @since 2.0
222   */
223  interface Entry<E> {
224
225    /**
226     * Returns the multiset element corresponding to this entry. Multiple calls to this method
227     * always return the same instance.
228     *
229     * @return the element corresponding to this entry
230     */
231    E getElement();
232
233    /**
234     * Returns the count of the associated element in the underlying multiset. This count may either
235     * be an unchanging snapshot of the count at the time the entry was retrieved, or a live view of
236     * the current count of the element in the multiset, depending on the implementation. Note that
237     * in the former case, this method can never return zero, while in the latter, it will return
238     * zero if all occurrences of the element were since removed from the multiset.
239     *
240     * @return the count of the element; never negative
241     */
242    int getCount();
243
244    /**
245     * {@inheritDoc}
246     *
247     * <p>Returns {@code true} if the given object is also a multiset entry and the two entries
248     * represent the same element and count. That is, two entries {@code a} and {@code b} are equal
249     * if:
250     *
251     * <pre>{@code
252     * Objects.equal(a.getElement(), b.getElement())
253     *     && a.getCount() == b.getCount()
254     * }</pre>
255     */
256    @Override
257    // TODO(kevinb): check this wrt TreeMultiset?
258    boolean equals(Object o);
259
260    /**
261     * {@inheritDoc}
262     *
263     * <p>The hash code of a multiset entry for element {@code element} and count {@code count} is
264     * defined as:
265     *
266     * <pre>{@code
267     * ((element == null) ? 0 : element.hashCode()) ^ count
268     * }</pre>
269     */
270    @Override
271    int hashCode();
272
273    /**
274     * Returns the canonical string representation of this entry, defined as follows. If the count
275     * for this entry is one, this is simply the string representation of the corresponding element.
276     * Otherwise, it is the string representation of the element, followed by the three characters
277     * {@code " x "} (space, letter x, space), followed by the count.
278     */
279    @Override
280    String toString();
281  }
282
283  // Comparison and hashing
284
285  /**
286   * Compares the specified object with this multiset for equality. Returns {@code true} if the
287   * given object is also a multiset and contains equal elements with equal counts, regardless of
288   * order.
289   */
290  @Override
291  // TODO(kevinb): caveats about equivalence-relation?
292  boolean equals(@NullableDecl Object object);
293
294  /**
295   * Returns the hash code for this multiset. This is defined as the sum of
296   *
297   * <pre>{@code
298   * ((element == null) ? 0 : element.hashCode()) ^ count(element)
299   * }</pre>
300   *
301   * <p>over all distinct elements in the multiset. It follows that a multiset and its entry set
302   * always have the same hash code.
303   */
304  @Override
305  int hashCode();
306
307  /**
308   * {@inheritDoc}
309   *
310   * <p>It is recommended, though not mandatory, that this method return the result of invoking
311   * {@link #toString} on the {@link #entrySet}, yielding a result such as {@code [a x 3, c, d x 2,
312   * e]}.
313   */
314  @Override
315  String toString();
316
317  // Refined Collection Methods
318
319  /**
320   * {@inheritDoc}
321   *
322   * <p>Elements that occur multiple times in the multiset will appear multiple times in this
323   * iterator, though not necessarily sequentially.
324   */
325  @Override
326  Iterator<E> iterator();
327
328  /**
329   * Determines whether this multiset contains the specified element.
330   *
331   * <p>This method refines {@link Collection#contains} to further specify that it <b>may not</b>
332   * throw an exception in response to {@code element} being null or of the wrong type.
333   *
334   * @param element the element to check for
335   * @return {@code true} if this multiset contains at least one occurrence of the element
336   */
337  @Override
338  boolean contains(@NullableDecl Object element);
339
340  /**
341   * Returns {@code true} if this multiset contains at least one occurrence of each element in the
342   * specified collection.
343   *
344   * <p>This method refines {@link Collection#containsAll} to further specify that it <b>may not</b>
345   * throw an exception in response to any of {@code elements} being null or of the wrong type.
346   *
347   * <p><b>Note:</b> this method does not take into account the occurrence count of an element in
348   * the two collections; it may still return {@code true} even if {@code elements} contains several
349   * occurrences of an element and this multiset contains only one. This is no different than any
350   * other collection type like {@link List}, but it may be unexpected to the user of a multiset.
351   *
352   * @param elements the collection of elements to be checked for containment in this multiset
353   * @return {@code true} if this multiset contains at least one occurrence of each element
354   *     contained in {@code elements}
355   * @throws NullPointerException if {@code elements} is null
356   */
357  @Override
358  boolean containsAll(Collection<?> elements);
359
360  /**
361   * Adds a single occurrence of the specified element to this multiset.
362   *
363   * <p>This method refines {@link Collection#add}, which only <i>ensures</i> the presence of the
364   * element, to further specify that a successful call must always increment the count of the
365   * element, and the overall size of the collection, by one.
366   *
367   * <p>To both add the element and obtain the previous count of that element, use {@link
368   * #add(Object, int) add}{@code (element, 1)} instead.
369   *
370   * @param element the element to add one occurrence of; may be null only if explicitly allowed by
371   *     the implementation
372   * @return {@code true} always, since this call is required to modify the multiset, unlike other
373   *     {@link Collection} types
374   * @throws NullPointerException if {@code element} is null and this implementation does not permit
375   *     null elements
376   * @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences of {@code element}
377   *     are already contained in this multiset
378   */
379  @CanIgnoreReturnValue
380  @Override
381  boolean add(E element);
382
383  /**
384   * Removes a <i>single</i> occurrence of the specified element from this multiset, if present.
385   *
386   * <p>This method refines {@link Collection#remove} to further specify that it <b>may not</b>
387   * throw an exception in response to {@code element} being null or of the wrong type.
388   *
389   * <p>To both remove the element and obtain the previous count of that element, use {@link
390   * #remove(Object, int) remove}{@code (element, 1)} instead.
391   *
392   * @param element the element to remove one occurrence of
393   * @return {@code true} if an occurrence was found and removed
394   */
395  @CanIgnoreReturnValue
396  @Override
397  boolean remove(@NullableDecl Object element);
398
399  /**
400   * {@inheritDoc}
401   *
402   * <p><b>Note:</b> This method ignores how often any element might appear in {@code c}, and only
403   * cares whether or not an element appears at all. If you wish to remove one occurrence in this
404   * multiset for every occurrence in {@code c}, see {@link Multisets#removeOccurrences(Multiset,
405   * Multiset)}.
406   *
407   * <p>This method refines {@link Collection#removeAll} to further specify that it <b>may not</b>
408   * throw an exception in response to any of {@code elements} being null or of the wrong type.
409   */
410  @CanIgnoreReturnValue
411  @Override
412  boolean removeAll(Collection<?> c);
413
414  /**
415   * {@inheritDoc}
416   *
417   * <p><b>Note:</b> This method ignores how often any element might appear in {@code c}, and only
418   * cares whether or not an element appears at all. If you wish to remove one occurrence in this
419   * multiset for every occurrence in {@code c}, see {@link Multisets#retainOccurrences(Multiset,
420   * Multiset)}.
421   *
422   * <p>This method refines {@link Collection#retainAll} to further specify that it <b>may not</b>
423   * throw an exception in response to any of {@code elements} being null or of the wrong type.
424   *
425   * @see Multisets#retainOccurrences(Multiset, Multiset)
426   */
427  @CanIgnoreReturnValue
428  @Override
429  boolean retainAll(Collection<?> c);
430}