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