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.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.CollectPreconditions.checkNonnegative;
022import static com.google.common.collect.CollectPreconditions.checkRemove;
023import static java.util.Objects.requireNonNull;
024
025import com.google.common.annotations.Beta;
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.base.Objects;
028import com.google.common.base.Predicate;
029import com.google.common.base.Predicates;
030import com.google.common.collect.Multiset.Entry;
031import com.google.common.math.IntMath;
032import com.google.common.primitives.Ints;
033import com.google.errorprone.annotations.CanIgnoreReturnValue;
034import com.google.errorprone.annotations.concurrent.LazyInit;
035import java.io.Serializable;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.Collections;
039import java.util.Comparator;
040import java.util.Iterator;
041import java.util.NoSuchElementException;
042import java.util.Set;
043import java.util.function.Function;
044import java.util.function.Supplier;
045import java.util.function.ToIntFunction;
046import java.util.stream.Collector;
047import javax.annotation.CheckForNull;
048import org.checkerframework.checker.nullness.qual.Nullable;
049
050/**
051 * Provides static utility methods for creating and working with {@link Multiset} instances.
052 *
053 * <p>See the Guava User Guide article on <a href=
054 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#multisets">{@code
055 * Multisets}</a>.
056 *
057 * @author Kevin Bourrillion
058 * @author Mike Bostock
059 * @author Louis Wasserman
060 * @since 2.0
061 */
062@GwtCompatible
063@ElementTypesAreNonnullByDefault
064public final class Multisets {
065  private Multisets() {}
066
067  /**
068   * Returns a {@code Collector} that accumulates elements into a multiset created via the specified
069   * {@code Supplier}, whose elements are the result of applying {@code elementFunction} to the
070   * inputs, with counts equal to the result of applying {@code countFunction} to the inputs.
071   * Elements are added in encounter order.
072   *
073   * <p>If the mapped elements contain duplicates (according to {@link Object#equals}), the element
074   * will be added more than once, with the count summed over all appearances of the element.
075   *
076   * <p>Note that {@code stream.collect(toMultiset(function, e -> 1, supplier))} is equivalent to
077   * {@code stream.map(function).collect(Collectors.toCollection(supplier))}.
078   *
079   * <p>To collect to an {@link ImmutableMultiset}, use {@link
080   * ImmutableMultiset#toImmutableMultiset}.
081   *
082   * @since 33.2.0 (available since 22.0 in guava-jre)
083   */
084  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
085  @IgnoreJRERequirement // Users will use this only if they're already using streams.
086  @Beta // TODO: b/288085449 - Remove.
087  public static <T extends @Nullable Object, E extends @Nullable Object, M extends Multiset<E>>
088      Collector<T, ?, M> toMultiset(
089          Function<? super T, E> elementFunction,
090          ToIntFunction<? super T> countFunction,
091          Supplier<M> multisetSupplier) {
092    return CollectCollectors.toMultiset(elementFunction, countFunction, multisetSupplier);
093  }
094
095  /**
096   * Returns an unmodifiable view of the specified multiset. Query operations on the returned
097   * multiset "read through" to the specified multiset, and attempts to modify the returned multiset
098   * result in an {@link UnsupportedOperationException}.
099   *
100   * <p>The returned multiset will be serializable if the specified multiset is serializable.
101   *
102   * @param multiset the multiset for which an unmodifiable view is to be generated
103   * @return an unmodifiable view of the multiset
104   */
105  public static <E extends @Nullable Object> Multiset<E> unmodifiableMultiset(
106      Multiset<? extends E> multiset) {
107    if (multiset instanceof UnmodifiableMultiset || multiset instanceof ImmutableMultiset) {
108      @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe
109      Multiset<E> result = (Multiset<E>) multiset;
110      return result;
111    }
112    return new UnmodifiableMultiset<>(checkNotNull(multiset));
113  }
114
115  /**
116   * Simply returns its argument.
117   *
118   * @deprecated no need to use this
119   * @since 10.0
120   */
121  @Deprecated
122  public static <E> Multiset<E> unmodifiableMultiset(ImmutableMultiset<E> multiset) {
123    return checkNotNull(multiset);
124  }
125
126  static class UnmodifiableMultiset<E extends @Nullable Object> extends ForwardingMultiset<E>
127      implements Serializable {
128    final Multiset<? extends E> delegate;
129
130    UnmodifiableMultiset(Multiset<? extends E> delegate) {
131      this.delegate = delegate;
132    }
133
134    @SuppressWarnings("unchecked")
135    @Override
136    protected Multiset<E> delegate() {
137      // This is safe because all non-covariant methods are overridden
138      return (Multiset<E>) delegate;
139    }
140
141    @LazyInit @CheckForNull transient Set<E> elementSet;
142
143    Set<E> createElementSet() {
144      return Collections.<E>unmodifiableSet(delegate.elementSet());
145    }
146
147    @Override
148    public Set<E> elementSet() {
149      Set<E> es = elementSet;
150      return (es == null) ? elementSet = createElementSet() : es;
151    }
152
153    @LazyInit @CheckForNull transient Set<Multiset.Entry<E>> entrySet;
154
155    @SuppressWarnings("unchecked")
156    @Override
157    public Set<Multiset.Entry<E>> entrySet() {
158      Set<Multiset.Entry<E>> es = entrySet;
159      return (es == null)
160          // Safe because the returned set is made unmodifiable and Entry
161          // itself is readonly
162          ? entrySet = (Set) Collections.unmodifiableSet(delegate.entrySet())
163          : es;
164    }
165
166    @Override
167    public Iterator<E> iterator() {
168      return Iterators.<E>unmodifiableIterator(delegate.iterator());
169    }
170
171    @Override
172    public boolean add(@ParametricNullness E element) {
173      throw new UnsupportedOperationException();
174    }
175
176    @Override
177    public int add(@ParametricNullness E element, int occurrences) {
178      throw new UnsupportedOperationException();
179    }
180
181    @Override
182    public boolean addAll(Collection<? extends E> elementsToAdd) {
183      throw new UnsupportedOperationException();
184    }
185
186    @Override
187    public boolean remove(@CheckForNull Object element) {
188      throw new UnsupportedOperationException();
189    }
190
191    @Override
192    public int remove(@CheckForNull Object element, int occurrences) {
193      throw new UnsupportedOperationException();
194    }
195
196    @Override
197    public boolean removeAll(Collection<?> elementsToRemove) {
198      throw new UnsupportedOperationException();
199    }
200
201    @Override
202    public boolean retainAll(Collection<?> elementsToRetain) {
203      throw new UnsupportedOperationException();
204    }
205
206    @Override
207    public void clear() {
208      throw new UnsupportedOperationException();
209    }
210
211    @Override
212    public int setCount(@ParametricNullness E element, int count) {
213      throw new UnsupportedOperationException();
214    }
215
216    @Override
217    public boolean setCount(@ParametricNullness E element, int oldCount, int newCount) {
218      throw new UnsupportedOperationException();
219    }
220
221    private static final long serialVersionUID = 0;
222  }
223
224  /**
225   * Returns an unmodifiable view of the specified sorted multiset. Query operations on the returned
226   * multiset "read through" to the specified multiset, and attempts to modify the returned multiset
227   * result in an {@link UnsupportedOperationException}.
228   *
229   * <p>The returned multiset will be serializable if the specified multiset is serializable.
230   *
231   * @param sortedMultiset the sorted multiset for which an unmodifiable view is to be generated
232   * @return an unmodifiable view of the multiset
233   * @since 11.0
234   */
235  public static <E extends @Nullable Object> SortedMultiset<E> unmodifiableSortedMultiset(
236      SortedMultiset<E> sortedMultiset) {
237    // it's in its own file so it can be emulated for GWT
238    return new UnmodifiableSortedMultiset<>(checkNotNull(sortedMultiset));
239  }
240
241  /**
242   * Returns an immutable multiset entry with the specified element and count. The entry will be
243   * serializable if {@code e} is.
244   *
245   * @param e the element to be associated with the returned entry
246   * @param n the count to be associated with the returned entry
247   * @throws IllegalArgumentException if {@code n} is negative
248   */
249  public static <E extends @Nullable Object> Multiset.Entry<E> immutableEntry(
250      @ParametricNullness E e, int n) {
251    return new ImmutableEntry<>(e, n);
252  }
253
254  static class ImmutableEntry<E extends @Nullable Object> extends AbstractEntry<E>
255      implements Serializable {
256    @ParametricNullness private final E element;
257    private final int count;
258
259    ImmutableEntry(@ParametricNullness E element, int count) {
260      this.element = element;
261      this.count = count;
262      checkNonnegative(count, "count");
263    }
264
265    @Override
266    @ParametricNullness
267    public final E getElement() {
268      return element;
269    }
270
271    @Override
272    public final int getCount() {
273      return count;
274    }
275
276    @CheckForNull
277    public ImmutableEntry<E> nextInBucket() {
278      return null;
279    }
280
281    private static final long serialVersionUID = 0;
282  }
283
284  /**
285   * Returns a view of the elements of {@code unfiltered} that satisfy a predicate. The returned
286   * multiset is a live view of {@code unfiltered}; changes to one affect the other.
287   *
288   * <p>The resulting multiset's iterators, and those of its {@code entrySet()} and {@code
289   * elementSet()}, do not support {@code remove()}. However, all other multiset methods supported
290   * by {@code unfiltered} are supported by the returned multiset. When given an element that
291   * doesn't satisfy the predicate, the multiset's {@code add()} and {@code addAll()} methods throw
292   * an {@link IllegalArgumentException}. When methods such as {@code removeAll()} and {@code
293   * clear()} are called on the filtered multiset, only elements that satisfy the filter will be
294   * removed from the underlying multiset.
295   *
296   * <p>The returned multiset isn't threadsafe or serializable, even if {@code unfiltered} is.
297   *
298   * <p>Many of the filtered multiset's methods, such as {@code size()}, iterate across every
299   * element in the underlying multiset and determine which elements satisfy the filter. When a live
300   * view is <i>not</i> needed, it may be faster to copy the returned multiset and use the copy.
301   *
302   * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
303   * {@link Predicate#apply}. Do not provide a predicate such as {@code
304   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
305   * Iterables#filter(Iterable, Class)} for related functionality.)
306   *
307   * @since 14.0
308   */
309  public static <E extends @Nullable Object> Multiset<E> filter(
310      Multiset<E> unfiltered, Predicate<? super E> predicate) {
311    if (unfiltered instanceof FilteredMultiset) {
312      // Support clear(), removeAll(), and retainAll() when filtering a filtered
313      // collection.
314      FilteredMultiset<E> filtered = (FilteredMultiset<E>) unfiltered;
315      Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate);
316      return new FilteredMultiset<>(filtered.unfiltered, combinedPredicate);
317    }
318    return new FilteredMultiset<>(unfiltered, predicate);
319  }
320
321  private static final class FilteredMultiset<E extends @Nullable Object> extends ViewMultiset<E> {
322    final Multiset<E> unfiltered;
323    final Predicate<? super E> predicate;
324
325    FilteredMultiset(Multiset<E> unfiltered, Predicate<? super E> predicate) {
326      this.unfiltered = checkNotNull(unfiltered);
327      this.predicate = checkNotNull(predicate);
328    }
329
330    @Override
331    public UnmodifiableIterator<E> iterator() {
332      return Iterators.filter(unfiltered.iterator(), predicate);
333    }
334
335    @Override
336    Set<E> createElementSet() {
337      return Sets.filter(unfiltered.elementSet(), predicate);
338    }
339
340    @Override
341    Iterator<E> elementIterator() {
342      throw new AssertionError("should never be called");
343    }
344
345    @Override
346    Set<Entry<E>> createEntrySet() {
347      return Sets.filter(
348          unfiltered.entrySet(),
349          new Predicate<Entry<E>>() {
350            @Override
351            public boolean apply(Entry<E> entry) {
352              return predicate.apply(entry.getElement());
353            }
354          });
355    }
356
357    @Override
358    Iterator<Entry<E>> entryIterator() {
359      throw new AssertionError("should never be called");
360    }
361
362    @Override
363    public int count(@CheckForNull Object element) {
364      int count = unfiltered.count(element);
365      if (count > 0) {
366        @SuppressWarnings("unchecked") // element is equal to an E
367        E e = (E) element;
368        return predicate.apply(e) ? count : 0;
369      }
370      return 0;
371    }
372
373    @Override
374    public int add(@ParametricNullness E element, int occurrences) {
375      checkArgument(
376          predicate.apply(element), "Element %s does not match predicate %s", element, predicate);
377      return unfiltered.add(element, occurrences);
378    }
379
380    @Override
381    public int remove(@CheckForNull Object element, int occurrences) {
382      checkNonnegative(occurrences, "occurrences");
383      if (occurrences == 0) {
384        return count(element);
385      } else {
386        return contains(element) ? unfiltered.remove(element, occurrences) : 0;
387      }
388    }
389  }
390
391  /**
392   * Returns the expected number of distinct elements given the specified elements. The number of
393   * distinct elements is only computed if {@code elements} is an instance of {@code Multiset};
394   * otherwise the default value of 11 is returned.
395   */
396  static int inferDistinctElements(Iterable<?> elements) {
397    if (elements instanceof Multiset) {
398      return ((Multiset<?>) elements).elementSet().size();
399    }
400    return 11; // initial capacity will be rounded up to 16
401  }
402
403  /**
404   * Returns an unmodifiable view of the union of two multisets. In the returned multiset, the count
405   * of each element is the <i>maximum</i> of its counts in the two backing multisets. The iteration
406   * order of the returned multiset matches that of the element set of {@code multiset1} followed by
407   * the members of the element set of {@code multiset2} that are not contained in {@code
408   * multiset1}, with repeated occurrences of the same element appearing consecutively.
409   *
410   * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different
411   * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are).
412   *
413   * @since 14.0
414   */
415  public static <E extends @Nullable Object> Multiset<E> union(
416      final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
417    checkNotNull(multiset1);
418    checkNotNull(multiset2);
419
420    return new ViewMultiset<E>() {
421      @Override
422      public boolean contains(@CheckForNull Object element) {
423        return multiset1.contains(element) || multiset2.contains(element);
424      }
425
426      @Override
427      public boolean isEmpty() {
428        return multiset1.isEmpty() && multiset2.isEmpty();
429      }
430
431      @Override
432      public int count(@CheckForNull Object element) {
433        return Math.max(multiset1.count(element), multiset2.count(element));
434      }
435
436      @Override
437      Set<E> createElementSet() {
438        return Sets.union(multiset1.elementSet(), multiset2.elementSet());
439      }
440
441      @Override
442      Iterator<E> elementIterator() {
443        throw new AssertionError("should never be called");
444      }
445
446      @Override
447      Iterator<Entry<E>> entryIterator() {
448        final Iterator<? extends Entry<? extends E>> iterator1 = multiset1.entrySet().iterator();
449        final Iterator<? extends Entry<? extends E>> iterator2 = multiset2.entrySet().iterator();
450        // TODO(lowasser): consider making the entries live views
451        return new AbstractIterator<Entry<E>>() {
452          @Override
453          @CheckForNull
454          protected Entry<E> computeNext() {
455            if (iterator1.hasNext()) {
456              Entry<? extends E> entry1 = iterator1.next();
457              E element = entry1.getElement();
458              int count = Math.max(entry1.getCount(), multiset2.count(element));
459              return immutableEntry(element, count);
460            }
461            while (iterator2.hasNext()) {
462              Entry<? extends E> entry2 = iterator2.next();
463              E element = entry2.getElement();
464              if (!multiset1.contains(element)) {
465                return immutableEntry(element, entry2.getCount());
466              }
467            }
468            return endOfData();
469          }
470        };
471      }
472    };
473  }
474
475  /**
476   * Returns an unmodifiable view of the intersection of two multisets. In the returned multiset,
477   * the count of each element is the <i>minimum</i> of its counts in the two backing multisets,
478   * with elements that would have a count of 0 not included. The iteration order of the returned
479   * multiset matches that of the element set of {@code multiset1}, with repeated occurrences of the
480   * same element appearing consecutively.
481   *
482   * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different
483   * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are).
484   *
485   * @since 2.0
486   */
487  public static <E extends @Nullable Object> Multiset<E> intersection(
488      final Multiset<E> multiset1, final Multiset<?> multiset2) {
489    checkNotNull(multiset1);
490    checkNotNull(multiset2);
491
492    return new ViewMultiset<E>() {
493      @Override
494      public int count(@CheckForNull Object element) {
495        int count1 = multiset1.count(element);
496        return (count1 == 0) ? 0 : Math.min(count1, multiset2.count(element));
497      }
498
499      @Override
500      Set<E> createElementSet() {
501        return Sets.intersection(multiset1.elementSet(), multiset2.elementSet());
502      }
503
504      @Override
505      Iterator<E> elementIterator() {
506        throw new AssertionError("should never be called");
507      }
508
509      @Override
510      Iterator<Entry<E>> entryIterator() {
511        final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator();
512        // TODO(lowasser): consider making the entries live views
513        return new AbstractIterator<Entry<E>>() {
514          @Override
515          @CheckForNull
516          protected Entry<E> computeNext() {
517            while (iterator1.hasNext()) {
518              Entry<E> entry1 = iterator1.next();
519              E element = entry1.getElement();
520              int count = Math.min(entry1.getCount(), multiset2.count(element));
521              if (count > 0) {
522                return immutableEntry(element, count);
523              }
524            }
525            return endOfData();
526          }
527        };
528      }
529    };
530  }
531
532  /**
533   * Returns an unmodifiable view of the sum of two multisets. In the returned multiset, the count
534   * of each element is the <i>sum</i> of its counts in the two backing multisets. The iteration
535   * order of the returned multiset matches that of the element set of {@code multiset1} followed by
536   * the members of the element set of {@code multiset2} that are not contained in {@code
537   * multiset1}, with repeated occurrences of the same element appearing consecutively.
538   *
539   * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different
540   * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are).
541   *
542   * @since 14.0
543   */
544  public static <E extends @Nullable Object> Multiset<E> sum(
545      final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
546    checkNotNull(multiset1);
547    checkNotNull(multiset2);
548
549    // TODO(lowasser): consider making the entries live views
550    return new ViewMultiset<E>() {
551      @Override
552      public boolean contains(@CheckForNull Object element) {
553        return multiset1.contains(element) || multiset2.contains(element);
554      }
555
556      @Override
557      public boolean isEmpty() {
558        return multiset1.isEmpty() && multiset2.isEmpty();
559      }
560
561      @Override
562      public int size() {
563        return IntMath.saturatedAdd(multiset1.size(), multiset2.size());
564      }
565
566      @Override
567      public int count(@CheckForNull Object element) {
568        return multiset1.count(element) + multiset2.count(element);
569      }
570
571      @Override
572      Set<E> createElementSet() {
573        return Sets.union(multiset1.elementSet(), multiset2.elementSet());
574      }
575
576      @Override
577      Iterator<E> elementIterator() {
578        throw new AssertionError("should never be called");
579      }
580
581      @Override
582      Iterator<Entry<E>> entryIterator() {
583        final Iterator<? extends Entry<? extends E>> iterator1 = multiset1.entrySet().iterator();
584        final Iterator<? extends Entry<? extends E>> iterator2 = multiset2.entrySet().iterator();
585        return new AbstractIterator<Entry<E>>() {
586          @Override
587          @CheckForNull
588          protected Entry<E> computeNext() {
589            if (iterator1.hasNext()) {
590              Entry<? extends E> entry1 = iterator1.next();
591              E element = entry1.getElement();
592              int count = entry1.getCount() + multiset2.count(element);
593              return immutableEntry(element, count);
594            }
595            while (iterator2.hasNext()) {
596              Entry<? extends E> entry2 = iterator2.next();
597              E element = entry2.getElement();
598              if (!multiset1.contains(element)) {
599                return immutableEntry(element, entry2.getCount());
600              }
601            }
602            return endOfData();
603          }
604        };
605      }
606    };
607  }
608
609  /**
610   * Returns an unmodifiable view of the difference of two multisets. In the returned multiset, the
611   * count of each element is the result of the <i>zero-truncated subtraction</i> of its count in
612   * the second multiset from its count in the first multiset, with elements that would have a count
613   * of 0 not included. The iteration order of the returned multiset matches that of the element set
614   * of {@code multiset1}, with repeated occurrences of the same element appearing consecutively.
615   *
616   * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different
617   * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are).
618   *
619   * @since 14.0
620   */
621  public static <E extends @Nullable Object> Multiset<E> difference(
622      final Multiset<E> multiset1, final Multiset<?> multiset2) {
623    checkNotNull(multiset1);
624    checkNotNull(multiset2);
625
626    // TODO(lowasser): consider making the entries live views
627    return new ViewMultiset<E>() {
628      @Override
629      public int count(@CheckForNull Object element) {
630        int count1 = multiset1.count(element);
631        return (count1 == 0) ? 0 : Math.max(0, count1 - multiset2.count(element));
632      }
633
634      @Override
635      public void clear() {
636        throw new UnsupportedOperationException();
637      }
638
639      @Override
640      Iterator<E> elementIterator() {
641        final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator();
642        return new AbstractIterator<E>() {
643          @Override
644          @CheckForNull
645          protected E computeNext() {
646            while (iterator1.hasNext()) {
647              Entry<E> entry1 = iterator1.next();
648              E element = entry1.getElement();
649              if (entry1.getCount() > multiset2.count(element)) {
650                return element;
651              }
652            }
653            return endOfData();
654          }
655        };
656      }
657
658      @Override
659      Iterator<Entry<E>> entryIterator() {
660        final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator();
661        return new AbstractIterator<Entry<E>>() {
662          @Override
663          @CheckForNull
664          protected Entry<E> computeNext() {
665            while (iterator1.hasNext()) {
666              Entry<E> entry1 = iterator1.next();
667              E element = entry1.getElement();
668              int count = entry1.getCount() - multiset2.count(element);
669              if (count > 0) {
670                return immutableEntry(element, count);
671              }
672            }
673            return endOfData();
674          }
675        };
676      }
677
678      @Override
679      int distinctElements() {
680        return Iterators.size(entryIterator());
681      }
682    };
683  }
684
685  /**
686   * Returns {@code true} if {@code subMultiset.count(o) <= superMultiset.count(o)} for all {@code
687   * o}.
688   *
689   * @since 10.0
690   */
691  @CanIgnoreReturnValue
692  public static boolean containsOccurrences(Multiset<?> superMultiset, Multiset<?> subMultiset) {
693    checkNotNull(superMultiset);
694    checkNotNull(subMultiset);
695    for (Entry<?> entry : subMultiset.entrySet()) {
696      int superCount = superMultiset.count(entry.getElement());
697      if (superCount < entry.getCount()) {
698        return false;
699      }
700    }
701    return true;
702  }
703
704  /**
705   * Modifies {@code multisetToModify} so that its count for an element {@code e} is at most {@code
706   * multisetToRetain.count(e)}.
707   *
708   * <p>To be precise, {@code multisetToModify.count(e)} is set to {@code
709   * Math.min(multisetToModify.count(e), multisetToRetain.count(e))}. This is similar to {@link
710   * #intersection(Multiset, Multiset) intersection} {@code (multisetToModify, multisetToRetain)},
711   * but mutates {@code multisetToModify} instead of returning a view.
712   *
713   * <p>In contrast, {@code multisetToModify.retainAll(multisetToRetain)} keeps all occurrences of
714   * elements that appear at all in {@code multisetToRetain}, and deletes all occurrences of all
715   * other elements.
716   *
717   * @return {@code true} if {@code multisetToModify} was changed as a result of this operation
718   * @since 10.0
719   */
720  @CanIgnoreReturnValue
721  public static boolean retainOccurrences(
722      Multiset<?> multisetToModify, Multiset<?> multisetToRetain) {
723    return retainOccurrencesImpl(multisetToModify, multisetToRetain);
724  }
725
726  /** Delegate implementation which cares about the element type. */
727  private static <E extends @Nullable Object> boolean retainOccurrencesImpl(
728      Multiset<E> multisetToModify, Multiset<?> occurrencesToRetain) {
729    checkNotNull(multisetToModify);
730    checkNotNull(occurrencesToRetain);
731    // Avoiding ConcurrentModificationExceptions is tricky.
732    Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator();
733    boolean changed = false;
734    while (entryIterator.hasNext()) {
735      Entry<E> entry = entryIterator.next();
736      int retainCount = occurrencesToRetain.count(entry.getElement());
737      if (retainCount == 0) {
738        entryIterator.remove();
739        changed = true;
740      } else if (retainCount < entry.getCount()) {
741        multisetToModify.setCount(entry.getElement(), retainCount);
742        changed = true;
743      }
744    }
745    return changed;
746  }
747
748  /**
749   * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, removes one
750   * occurrence of {@code e} in {@code multisetToModify}.
751   *
752   * <p>Equivalently, this method modifies {@code multisetToModify} so that {@code
753   * multisetToModify.count(e)} is set to {@code Math.max(0, multisetToModify.count(e) -
754   * Iterables.frequency(occurrencesToRemove, e))}.
755   *
756   * <p>This is <i>not</i> the same as {@code multisetToModify.} {@link Multiset#removeAll
757   * removeAll}{@code (occurrencesToRemove)}, which removes all occurrences of elements that appear
758   * in {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent to, albeit
759   * sometimes more efficient than, the following:
760   *
761   * <pre>{@code
762   * for (E e : occurrencesToRemove) {
763   *   multisetToModify.remove(e);
764   * }
765   * }</pre>
766   *
767   * @return {@code true} if {@code multisetToModify} was changed as a result of this operation
768   * @since 18.0 (present in 10.0 with a requirement that the second parameter be a {@code
769   *     Multiset})
770   */
771  @CanIgnoreReturnValue
772  public static boolean removeOccurrences(
773      Multiset<?> multisetToModify, Iterable<?> occurrencesToRemove) {
774    if (occurrencesToRemove instanceof Multiset) {
775      return removeOccurrences(multisetToModify, (Multiset<?>) occurrencesToRemove);
776    } else {
777      checkNotNull(multisetToModify);
778      checkNotNull(occurrencesToRemove);
779      boolean changed = false;
780      for (Object o : occurrencesToRemove) {
781        changed |= multisetToModify.remove(o);
782      }
783      return changed;
784    }
785  }
786
787  /**
788   * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, removes one
789   * occurrence of {@code e} in {@code multisetToModify}.
790   *
791   * <p>Equivalently, this method modifies {@code multisetToModify} so that {@code
792   * multisetToModify.count(e)} is set to {@code Math.max(0, multisetToModify.count(e) -
793   * occurrencesToRemove.count(e))}.
794   *
795   * <p>This is <i>not</i> the same as {@code multisetToModify.} {@link Multiset#removeAll
796   * removeAll}{@code (occurrencesToRemove)}, which removes all occurrences of elements that appear
797   * in {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent to, albeit
798   * sometimes more efficient than, the following:
799   *
800   * <pre>{@code
801   * for (E e : occurrencesToRemove) {
802   *   multisetToModify.remove(e);
803   * }
804   * }</pre>
805   *
806   * @return {@code true} if {@code multisetToModify} was changed as a result of this operation
807   * @since 10.0 (missing in 18.0 when only the overload taking an {@code Iterable} was present)
808   */
809  @CanIgnoreReturnValue
810  public static boolean removeOccurrences(
811      Multiset<?> multisetToModify, Multiset<?> occurrencesToRemove) {
812    checkNotNull(multisetToModify);
813    checkNotNull(occurrencesToRemove);
814
815    boolean changed = false;
816    Iterator<? extends Entry<?>> entryIterator = multisetToModify.entrySet().iterator();
817    while (entryIterator.hasNext()) {
818      Entry<?> entry = entryIterator.next();
819      int removeCount = occurrencesToRemove.count(entry.getElement());
820      if (removeCount >= entry.getCount()) {
821        entryIterator.remove();
822        changed = true;
823      } else if (removeCount > 0) {
824        multisetToModify.remove(entry.getElement(), removeCount);
825        changed = true;
826      }
827    }
828    return changed;
829  }
830
831  /**
832   * Implementation of the {@code equals}, {@code hashCode}, and {@code toString} methods of {@link
833   * Multiset.Entry}.
834   */
835  abstract static class AbstractEntry<E extends @Nullable Object> implements Multiset.Entry<E> {
836    /**
837     * Indicates whether an object equals this entry, following the behavior specified in {@link
838     * Multiset.Entry#equals}.
839     */
840    @Override
841    public boolean equals(@CheckForNull Object object) {
842      if (object instanceof Multiset.Entry) {
843        Multiset.Entry<?> that = (Multiset.Entry<?>) object;
844        return this.getCount() == that.getCount()
845            && Objects.equal(this.getElement(), that.getElement());
846      }
847      return false;
848    }
849
850    /**
851     * Return this entry's hash code, following the behavior specified in {@link
852     * Multiset.Entry#hashCode}.
853     */
854    @Override
855    public int hashCode() {
856      E e = getElement();
857      return ((e == null) ? 0 : e.hashCode()) ^ getCount();
858    }
859
860    /**
861     * Returns a string representation of this multiset entry. The string representation consists of
862     * the associated element if the associated count is one, and otherwise the associated element
863     * followed by the characters " x " (space, x and space) followed by the count. Elements and
864     * counts are converted to strings as by {@code String.valueOf}.
865     */
866    @Override
867    public String toString() {
868      String text = String.valueOf(getElement());
869      int n = getCount();
870      return (n == 1) ? text : (text + " x " + n);
871    }
872  }
873
874  /** An implementation of {@link Multiset#equals}. */
875  static boolean equalsImpl(Multiset<?> multiset, @CheckForNull Object object) {
876    if (object == multiset) {
877      return true;
878    }
879    if (object instanceof Multiset) {
880      Multiset<?> that = (Multiset<?>) object;
881      /*
882       * We can't simply check whether the entry sets are equal, since that
883       * approach fails when a TreeMultiset has a comparator that returns 0
884       * when passed unequal elements.
885       */
886
887      if (multiset.size() != that.size() || multiset.entrySet().size() != that.entrySet().size()) {
888        return false;
889      }
890      for (Entry<?> entry : that.entrySet()) {
891        if (multiset.count(entry.getElement()) != entry.getCount()) {
892          return false;
893        }
894      }
895      return true;
896    }
897    return false;
898  }
899
900  /** An implementation of {@link Multiset#addAll}. */
901  static <E extends @Nullable Object> boolean addAllImpl(
902      Multiset<E> self, Collection<? extends E> elements) {
903    checkNotNull(self);
904    checkNotNull(elements);
905    if (elements instanceof Multiset) {
906      return addAllImpl(self, cast(elements));
907    } else if (elements.isEmpty()) {
908      return false;
909    } else {
910      return Iterators.addAll(self, elements.iterator());
911    }
912  }
913
914  /** A specialization of {@code addAllImpl} for when {@code elements} is itself a Multiset. */
915  private static <E extends @Nullable Object> boolean addAllImpl(
916      Multiset<E> self, Multiset<? extends E> elements) {
917    // It'd be nice if we could specialize for ImmutableMultiset here without also retaining
918    // its code when it's not in scope...
919    if (elements instanceof AbstractMapBasedMultiset) {
920      return addAllImpl(self, (AbstractMapBasedMultiset<? extends E>) elements);
921    } else if (elements.isEmpty()) {
922      return false;
923    } else {
924      for (Multiset.Entry<? extends E> entry : elements.entrySet()) {
925        self.add(entry.getElement(), entry.getCount());
926      }
927      return true;
928    }
929  }
930
931  /**
932   * A specialization of {@code addAllImpl} for when {@code elements} is an
933   * AbstractMapBasedMultiset.
934   */
935  private static <E extends @Nullable Object> boolean addAllImpl(
936      Multiset<E> self, AbstractMapBasedMultiset<? extends E> elements) {
937    if (elements.isEmpty()) {
938      return false;
939    }
940    elements.addTo(self);
941    return true;
942  }
943
944  /** An implementation of {@link Multiset#removeAll}. */
945  static boolean removeAllImpl(Multiset<?> self, Collection<?> elementsToRemove) {
946    Collection<?> collection =
947        (elementsToRemove instanceof Multiset)
948            ? ((Multiset<?>) elementsToRemove).elementSet()
949            : elementsToRemove;
950
951    return self.elementSet().removeAll(collection);
952  }
953
954  /** An implementation of {@link Multiset#retainAll}. */
955  static boolean retainAllImpl(Multiset<?> self, Collection<?> elementsToRetain) {
956    checkNotNull(elementsToRetain);
957    Collection<?> collection =
958        (elementsToRetain instanceof Multiset)
959            ? ((Multiset<?>) elementsToRetain).elementSet()
960            : elementsToRetain;
961
962    return self.elementSet().retainAll(collection);
963  }
964
965  /** An implementation of {@link Multiset#setCount(Object, int)}. */
966  static <E extends @Nullable Object> int setCountImpl(
967      Multiset<E> self, @ParametricNullness E element, int count) {
968    checkNonnegative(count, "count");
969
970    int oldCount = self.count(element);
971
972    int delta = count - oldCount;
973    if (delta > 0) {
974      self.add(element, delta);
975    } else if (delta < 0) {
976      self.remove(element, -delta);
977    }
978
979    return oldCount;
980  }
981
982  /** An implementation of {@link Multiset#setCount(Object, int, int)}. */
983  static <E extends @Nullable Object> boolean setCountImpl(
984      Multiset<E> self, @ParametricNullness E element, int oldCount, int newCount) {
985    checkNonnegative(oldCount, "oldCount");
986    checkNonnegative(newCount, "newCount");
987
988    if (self.count(element) == oldCount) {
989      self.setCount(element, newCount);
990      return true;
991    } else {
992      return false;
993    }
994  }
995
996  static <E extends @Nullable Object> Iterator<E> elementIterator(
997      Iterator<Entry<E>> entryIterator) {
998    return new TransformedIterator<Entry<E>, E>(entryIterator) {
999      @Override
1000      @ParametricNullness
1001      E transform(Entry<E> entry) {
1002        return entry.getElement();
1003      }
1004    };
1005  }
1006
1007  abstract static class ElementSet<E extends @Nullable Object> extends Sets.ImprovedAbstractSet<E> {
1008    abstract Multiset<E> multiset();
1009
1010    @Override
1011    public void clear() {
1012      multiset().clear();
1013    }
1014
1015    @Override
1016    public boolean contains(@CheckForNull Object o) {
1017      return multiset().contains(o);
1018    }
1019
1020    @Override
1021    public boolean containsAll(Collection<?> c) {
1022      return multiset().containsAll(c);
1023    }
1024
1025    @Override
1026    public boolean isEmpty() {
1027      return multiset().isEmpty();
1028    }
1029
1030    @Override
1031    public abstract Iterator<E> iterator();
1032
1033    @Override
1034    public boolean remove(@CheckForNull Object o) {
1035      return multiset().remove(o, Integer.MAX_VALUE) > 0;
1036    }
1037
1038    @Override
1039    public int size() {
1040      return multiset().entrySet().size();
1041    }
1042  }
1043
1044  abstract static class EntrySet<E extends @Nullable Object>
1045      extends Sets.ImprovedAbstractSet<Entry<E>> {
1046    abstract Multiset<E> multiset();
1047
1048    @Override
1049    public boolean contains(@CheckForNull Object o) {
1050      if (o instanceof Entry) {
1051        Entry<?> entry = (Entry<?>) o;
1052        if (entry.getCount() <= 0) {
1053          return false;
1054        }
1055        int count = multiset().count(entry.getElement());
1056        return count == entry.getCount();
1057      }
1058      return false;
1059    }
1060
1061    @Override
1062    public boolean remove(@CheckForNull Object object) {
1063      if (object instanceof Multiset.Entry) {
1064        Entry<?> entry = (Entry<?>) object;
1065        Object element = entry.getElement();
1066        int entryCount = entry.getCount();
1067        if (entryCount != 0) {
1068          // Safe as long as we never add a new entry, which we won't.
1069          // (Presumably it can still throw CCE/NPE but only if the underlying Multiset does.)
1070          @SuppressWarnings({"unchecked", "nullness"})
1071          Multiset<@Nullable Object> multiset = (Multiset<@Nullable Object>) multiset();
1072          return multiset.setCount(element, entryCount, 0);
1073        }
1074      }
1075      return false;
1076    }
1077
1078    @Override
1079    public void clear() {
1080      multiset().clear();
1081    }
1082  }
1083
1084  /** An implementation of {@link Multiset#iterator}. */
1085  static <E extends @Nullable Object> Iterator<E> iteratorImpl(Multiset<E> multiset) {
1086    return new MultisetIteratorImpl<>(multiset, multiset.entrySet().iterator());
1087  }
1088
1089  static final class MultisetIteratorImpl<E extends @Nullable Object> implements Iterator<E> {
1090    private final Multiset<E> multiset;
1091    private final Iterator<Entry<E>> entryIterator;
1092    @CheckForNull private Entry<E> currentEntry;
1093
1094    /** Count of subsequent elements equal to current element */
1095    private int laterCount;
1096
1097    /** Count of all elements equal to current element */
1098    private int totalCount;
1099
1100    private boolean canRemove;
1101
1102    MultisetIteratorImpl(Multiset<E> multiset, Iterator<Entry<E>> entryIterator) {
1103      this.multiset = multiset;
1104      this.entryIterator = entryIterator;
1105    }
1106
1107    @Override
1108    public boolean hasNext() {
1109      return laterCount > 0 || entryIterator.hasNext();
1110    }
1111
1112    @Override
1113    @ParametricNullness
1114    public E next() {
1115      if (!hasNext()) {
1116        throw new NoSuchElementException();
1117      }
1118      if (laterCount == 0) {
1119        currentEntry = entryIterator.next();
1120        totalCount = laterCount = currentEntry.getCount();
1121      }
1122      laterCount--;
1123      canRemove = true;
1124      /*
1125       * requireNonNull is safe because laterCount starts at 0, forcing us to initialize
1126       * currentEntry above. After that, we never clear it.
1127       */
1128      return requireNonNull(currentEntry).getElement();
1129    }
1130
1131    @Override
1132    public void remove() {
1133      checkRemove(canRemove);
1134      if (totalCount == 1) {
1135        entryIterator.remove();
1136      } else {
1137        /*
1138         * requireNonNull is safe because canRemove is set to true only after we initialize
1139         * currentEntry (which we never subsequently clear).
1140         */
1141        multiset.remove(requireNonNull(currentEntry).getElement());
1142      }
1143      totalCount--;
1144      canRemove = false;
1145    }
1146  }
1147
1148  /** An implementation of {@link Multiset#size}. */
1149  static int linearTimeSizeImpl(Multiset<?> multiset) {
1150    long size = 0;
1151    for (Entry<?> entry : multiset.entrySet()) {
1152      size += entry.getCount();
1153    }
1154    return Ints.saturatedCast(size);
1155  }
1156
1157  /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */
1158  static <T extends @Nullable Object> Multiset<T> cast(Iterable<T> iterable) {
1159    return (Multiset<T>) iterable;
1160  }
1161
1162  /**
1163   * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order puts
1164   * the highest count first, with ties broken by the iteration order of the original multiset.
1165   *
1166   * @since 11.0
1167   */
1168  public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) {
1169    @SuppressWarnings("unchecked") // generics+arrays
1170    // TODO(cpovirk): Consider storing an Entry<?> instead of Entry<E>.
1171    Entry<E>[] entries = (Entry<E>[]) multiset.entrySet().toArray((Entry<E>[]) new Entry<?>[0]);
1172    Arrays.sort(entries, DecreasingCount.INSTANCE);
1173    return ImmutableMultiset.copyFromEntries(Arrays.asList(entries));
1174  }
1175
1176  private static final class DecreasingCount implements Comparator<Entry<?>> {
1177    static final Comparator<Entry<?>> INSTANCE = new DecreasingCount();
1178
1179    @Override
1180    public int compare(Entry<?> entry1, Entry<?> entry2) {
1181      return entry2.getCount() - entry1.getCount(); // subtracting two nonnegative integers
1182    }
1183  }
1184
1185  /**
1186   * An {@link AbstractMultiset} with additional default implementations, some of them linear-time
1187   * implementations in terms of {@code elementSet} and {@code entrySet}.
1188   */
1189  private abstract static class ViewMultiset<E extends @Nullable Object>
1190      extends AbstractMultiset<E> {
1191    @Override
1192    public int size() {
1193      return linearTimeSizeImpl(this);
1194    }
1195
1196    @Override
1197    public void clear() {
1198      elementSet().clear();
1199    }
1200
1201    @Override
1202    public Iterator<E> iterator() {
1203      return iteratorImpl(this);
1204    }
1205
1206    @Override
1207    int distinctElements() {
1208      return elementSet().size();
1209    }
1210  }
1211}