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