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