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.lang.Math.max;
024import static java.lang.Math.min;
025import static java.util.Arrays.asList;
026import static java.util.Objects.requireNonNull;
027
028import com.google.common.annotations.GwtCompatible;
029import com.google.common.base.Objects;
030import com.google.common.base.Predicate;
031import com.google.common.base.Predicates;
032import com.google.common.collect.Multiset.Entry;
033import com.google.common.math.IntMath;
034import com.google.common.primitives.Ints;
035import com.google.errorprone.annotations.CanIgnoreReturnValue;
036import com.google.errorprone.annotations.concurrent.LazyInit;
037import java.io.Serializable;
038import java.util.Arrays;
039import java.util.Collection;
040import java.util.Collections;
041import java.util.Comparator;
042import java.util.Iterator;
043import java.util.NoSuchElementException;
044import java.util.Set;
045import java.util.Spliterator;
046import java.util.function.Function;
047import java.util.function.Supplier;
048import java.util.function.ToIntFunction;
049import java.util.stream.Collector;
050import org.jspecify.annotations.Nullable;
051
052/**
053 * Provides static utility methods for creating and working with {@link Multiset} instances.
054 *
055 * <p>See the Guava User Guide article on <a href=
056 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#multisets">{@code
057 * Multisets}</a>.
058 *
059 * @author Kevin Bourrillion
060 * @author Mike Bostock
061 * @author Louis Wasserman
062 * @since 2.0
063 */
064@GwtCompatible
065public final class Multisets {
066  private Multisets() {}
067
068  /**
069   * Returns a {@code Collector} that accumulates elements into a multiset created via the specified
070   * {@code Supplier}, whose elements are the result of applying {@code elementFunction} to the
071   * inputs, with counts equal to the result of applying {@code countFunction} to the inputs.
072   * Elements are added in encounter order.
073   *
074   * <p>If the mapped elements contain duplicates (according to {@link Object#equals}), the element
075   * will be added more than once, with the count summed over all appearances of the element.
076   *
077   * <p>Note that {@code stream.collect(toMultiset(function, e -> 1, supplier))} is equivalent to
078   * {@code stream.map(function).collect(Collectors.toCollection(supplier))}.
079   *
080   * <p>To collect to an {@link ImmutableMultiset}, use {@link
081   * ImmutableMultiset#toImmutableMultiset}.
082   *
083   * @since 22.0
084   */
085  public static <T extends @Nullable Object, E extends @Nullable Object, M extends Multiset<E>>
086      Collector<T, ?, M> toMultiset(
087          Function<? super T, E> elementFunction,
088          ToIntFunction<? super T> countFunction,
089          Supplier<M> multisetSupplier) {
090    return CollectCollectors.toMultiset(elementFunction, countFunction, multisetSupplier);
091  }
092
093  /**
094   * Returns an unmodifiable view of the specified multiset. Query operations on the returned
095   * multiset "read through" to the specified multiset, and attempts to modify the returned multiset
096   * result in an {@link UnsupportedOperationException}.
097   *
098   * <p>The returned multiset will be serializable if the specified multiset is serializable.
099   *
100   * @param multiset the multiset for which an unmodifiable view is to be generated
101   * @return an unmodifiable view of the multiset
102   */
103  public static <E extends @Nullable Object> Multiset<E> unmodifiableMultiset(
104      Multiset<? extends E> multiset) {
105    if (multiset instanceof UnmodifiableMultiset || multiset instanceof ImmutableMultiset) {
106      @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe
107      Multiset<E> result = (Multiset<E>) multiset;
108      return result;
109    }
110    return new UnmodifiableMultiset<>(checkNotNull(multiset));
111  }
112
113  /**
114   * Simply returns its argument.
115   *
116   * @deprecated no need to use this
117   * @since 10.0
118   */
119  @Deprecated
120  public static <E> Multiset<E> unmodifiableMultiset(ImmutableMultiset<E> multiset) {
121    return checkNotNull(multiset);
122  }
123
124  static class UnmodifiableMultiset<E extends @Nullable Object> extends ForwardingMultiset<E>
125      implements Serializable {
126    final Multiset<? extends E> delegate;
127
128    UnmodifiableMultiset(Multiset<? extends E> delegate) {
129      this.delegate = delegate;
130    }
131
132    @SuppressWarnings("unchecked")
133    @Override
134    protected Multiset<E> delegate() {
135      // This is safe because all non-covariant methods are overridden
136      return (Multiset<E>) delegate;
137    }
138
139    @LazyInit transient @Nullable Set<E> elementSet;
140
141    Set<E> createElementSet() {
142      return Collections.<E>unmodifiableSet(delegate.elementSet());
143    }
144
145    @Override
146    public Set<E> elementSet() {
147      Set<E> es = elementSet;
148      return (es == null) ? elementSet = createElementSet() : es;
149    }
150
151    @LazyInit transient @Nullable Set<Multiset.Entry<E>> entrySet;
152
153    @SuppressWarnings("unchecked")
154    @Override
155    public Set<Multiset.Entry<E>> entrySet() {
156      Set<Multiset.Entry<E>> es = entrySet;
157      return (es == null)
158          // Safe because the returned set is made unmodifiable and Entry
159          // itself is readonly
160          ? entrySet = (Set) Collections.unmodifiableSet(delegate.entrySet())
161          : es;
162    }
163
164    @Override
165    public Iterator<E> iterator() {
166      return Iterators.<E>unmodifiableIterator(delegate.iterator());
167    }
168
169    @Override
170    public boolean add(@ParametricNullness E element) {
171      throw new UnsupportedOperationException();
172    }
173
174    @Override
175    public int add(@ParametricNullness E element, int occurrences) {
176      throw new UnsupportedOperationException();
177    }
178
179    @Override
180    public boolean addAll(Collection<? extends E> elementsToAdd) {
181      throw new UnsupportedOperationException();
182    }
183
184    @Override
185    public boolean remove(@Nullable Object element) {
186      throw new UnsupportedOperationException();
187    }
188
189    @Override
190    public int remove(@Nullable Object element, int occurrences) {
191      throw new UnsupportedOperationException();
192    }
193
194    @Override
195    public boolean removeAll(Collection<?> elementsToRemove) {
196      throw new UnsupportedOperationException();
197    }
198
199    @Override
200    public boolean removeIf(java.util.function.Predicate<? super E> filter) {
201      throw new UnsupportedOperationException();
202    }
203
204    @Override
205    public boolean retainAll(Collection<?> elementsToRetain) {
206      throw new UnsupportedOperationException();
207    }
208
209    @Override
210    public void clear() {
211      throw new UnsupportedOperationException();
212    }
213
214    @Override
215    public int setCount(@ParametricNullness E element, int count) {
216      throw new UnsupportedOperationException();
217    }
218
219    @Override
220    public boolean setCount(@ParametricNullness E element, int oldCount, int newCount) {
221      throw new UnsupportedOperationException();
222    }
223
224    private static final long serialVersionUID = 0;
225  }
226
227  /**
228   * Returns an unmodifiable view of the specified sorted multiset. Query operations on the returned
229   * multiset "read through" to the specified multiset, and attempts to modify the returned multiset
230   * result in an {@link UnsupportedOperationException}.
231   *
232   * <p>The returned multiset will be serializable if the specified multiset is serializable.
233   *
234   * @param sortedMultiset the sorted multiset for which an unmodifiable view is to be generated
235   * @return an unmodifiable view of the multiset
236   * @since 11.0
237   */
238  public static <E extends @Nullable Object> SortedMultiset<E> unmodifiableSortedMultiset(
239      SortedMultiset<E> sortedMultiset) {
240    // it's in its own file so it can be emulated for GWT
241    return new UnmodifiableSortedMultiset<>(checkNotNull(sortedMultiset));
242  }
243
244  /**
245   * Returns an immutable multiset entry with the specified element and count. The entry will be
246   * serializable if {@code e} is.
247   *
248   * @param e the element to be associated with the returned entry
249   * @param n the count to be associated with the returned entry
250   * @throws IllegalArgumentException if {@code n} is negative
251   */
252  public static <E extends @Nullable Object> Multiset.Entry<E> immutableEntry(
253      @ParametricNullness E e, int n) {
254    return new ImmutableEntry<>(e, n);
255  }
256
257  static class ImmutableEntry<E extends @Nullable Object> extends AbstractEntry<E>
258      implements Serializable {
259    @ParametricNullness private final E element;
260    private final int count;
261
262    ImmutableEntry(@ParametricNullness E element, int count) {
263      this.element = element;
264      this.count = count;
265      checkNonnegative(count, "count");
266    }
267
268    @Override
269    @ParametricNullness
270    public final E getElement() {
271      return element;
272    }
273
274    @Override
275    public final int getCount() {
276      return count;
277    }
278
279    public @Nullable ImmutableEntry<E> nextInBucket() {
280      return null;
281    }
282
283    private static final long serialVersionUID = 0;
284  }
285
286  /**
287   * Returns a view of the elements of {@code unfiltered} that satisfy a predicate. The returned
288   * multiset is a live view of {@code unfiltered}; changes to one affect the other.
289   *
290   * <p>The resulting multiset's iterators, and those of its {@code entrySet()} and {@code
291   * elementSet()}, do not support {@code remove()}. However, all other multiset methods supported
292   * by {@code unfiltered} are supported by the returned multiset. When given an element that
293   * doesn't satisfy the predicate, the multiset's {@code add()} and {@code addAll()} methods throw
294   * an {@link IllegalArgumentException}. When methods such as {@code removeAll()} and {@code
295   * clear()} are called on the filtered multiset, only elements that satisfy the filter will be
296   * removed from the underlying multiset.
297   *
298   * <p>The returned multiset isn't threadsafe or serializable, even if {@code unfiltered} is.
299   *
300   * <p>Many of the filtered multiset's methods, such as {@code size()}, iterate across every
301   * element in the underlying multiset and determine which elements satisfy the filter. When a live
302   * view is <i>not</i> needed, it may be faster to copy the returned multiset and use the copy.
303   *
304   * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at
305   * {@link Predicate#apply}. Do not provide a predicate such as {@code
306   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link
307   * Iterables#filter(Iterable, Class)} for related functionality.)
308   *
309   * @since 14.0
310   */
311  public static <E extends @Nullable Object> Multiset<E> filter(
312      Multiset<E> unfiltered, Predicate<? super E> predicate) {
313    if (unfiltered instanceof FilteredMultiset) {
314      // Support clear(), removeAll(), and retainAll() when filtering a filtered
315      // collection.
316      FilteredMultiset<E> filtered = (FilteredMultiset<E>) unfiltered;
317      Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate);
318      return new FilteredMultiset<>(filtered.unfiltered, combinedPredicate);
319    }
320    return new FilteredMultiset<>(unfiltered, predicate);
321  }
322
323  private static final class FilteredMultiset<E extends @Nullable Object> extends ViewMultiset<E> {
324    final Multiset<E> unfiltered;
325    final Predicate<? super E> predicate;
326
327    FilteredMultiset(Multiset<E> unfiltered, Predicate<? super E> predicate) {
328      this.unfiltered = checkNotNull(unfiltered);
329      this.predicate = checkNotNull(predicate);
330    }
331
332    @Override
333    public UnmodifiableIterator<E> iterator() {
334      return Iterators.filter(unfiltered.iterator(), predicate);
335    }
336
337    @Override
338    Set<E> createElementSet() {
339      return Sets.filter(unfiltered.elementSet(), predicate);
340    }
341
342    @Override
343    Iterator<E> elementIterator() {
344      throw new AssertionError("should never be called");
345    }
346
347    @Override
348    Set<Entry<E>> createEntrySet() {
349      return Sets.filter(
350          unfiltered.entrySet(),
351          new Predicate<Entry<E>>() {
352            @Override
353            public boolean apply(Entry<E> entry) {
354              return predicate.apply(entry.getElement());
355            }
356          });
357    }
358
359    @Override
360    Iterator<Entry<E>> entryIterator() {
361      throw new AssertionError("should never be called");
362    }
363
364    @Override
365    public int count(@Nullable Object element) {
366      int count = unfiltered.count(element);
367      if (count > 0) {
368        @SuppressWarnings("unchecked") // element is equal to an E
369        E e = (E) element;
370        return predicate.apply(e) ? count : 0;
371      }
372      return 0;
373    }
374
375    @Override
376    public int add(@ParametricNullness E element, int occurrences) {
377      checkArgument(
378          predicate.apply(element), "Element %s does not match predicate %s", element, predicate);
379      return unfiltered.add(element, occurrences);
380    }
381
382    @Override
383    public int remove(@Nullable Object element, int occurrences) {
384      checkNonnegative(occurrences, "occurrences");
385      if (occurrences == 0) {
386        return count(element);
387      } else {
388        return contains(element) ? unfiltered.remove(element, occurrences) : 0;
389      }
390    }
391  }
392
393  /**
394   * Returns the expected number of distinct elements given the specified elements. The number of
395   * distinct elements is only computed if {@code elements} is an instance of {@code Multiset};
396   * otherwise the default value of 11 is returned.
397   */
398  static int inferDistinctElements(Iterable<?> elements) {
399    if (elements instanceof Multiset) {
400      return ((Multiset<?>) elements).elementSet().size();
401    }
402    return 11; // initial capacity will be rounded up to 16
403  }
404
405  /**
406   * Returns an unmodifiable view of the union of two multisets. In the returned multiset, the count
407   * of each element is the <i>maximum</i> of its counts in the two backing multisets. The iteration
408   * order of the returned multiset matches that of the element set of {@code multiset1} followed by
409   * the members of the element set of {@code multiset2} that are not contained in {@code
410   * multiset1}, with repeated occurrences of the same element appearing consecutively.
411   *
412   * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different
413   * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are).
414   *
415   * @since 14.0
416   */
417  public static <E extends @Nullable Object> Multiset<E> union(
418      final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
419    checkNotNull(multiset1);
420    checkNotNull(multiset2);
421
422    return new ViewMultiset<E>() {
423      @Override
424      public boolean contains(@Nullable Object element) {
425        return multiset1.contains(element) || multiset2.contains(element);
426      }
427
428      @Override
429      public boolean isEmpty() {
430        return multiset1.isEmpty() && multiset2.isEmpty();
431      }
432
433      @Override
434      public int count(@Nullable Object element) {
435        return max(multiset1.count(element), multiset2.count(element));
436      }
437
438      @Override
439      Set<E> createElementSet() {
440        return Sets.union(multiset1.elementSet(), multiset2.elementSet());
441      }
442
443      @Override
444      Iterator<E> elementIterator() {
445        throw new AssertionError("should never be called");
446      }
447
448      @Override
449      Iterator<Entry<E>> entryIterator() {
450        final Iterator<? extends Entry<? extends E>> iterator1 = multiset1.entrySet().iterator();
451        final Iterator<? extends Entry<? extends E>> iterator2 = multiset2.entrySet().iterator();
452        // TODO(lowasser): consider making the entries live views
453        return new AbstractIterator<Entry<E>>() {
454          @Override
455          protected @Nullable Entry<E> computeNext() {
456            if (iterator1.hasNext()) {
457              Entry<? extends E> entry1 = iterator1.next();
458              E element = entry1.getElement();
459              int count = max(entry1.getCount(), multiset2.count(element));
460              return immutableEntry(element, count);
461            }
462            while (iterator2.hasNext()) {
463              Entry<? extends E> entry2 = iterator2.next();
464              E element = entry2.getElement();
465              if (!multiset1.contains(element)) {
466                return immutableEntry(element, entry2.getCount());
467              }
468            }
469            return endOfData();
470          }
471        };
472      }
473    };
474  }
475
476  /**
477   * Returns an unmodifiable view of the intersection of two multisets. In the returned multiset,
478   * the count of each element is the <i>minimum</i> of its counts in the two backing multisets,
479   * with elements that would have a count of 0 not included. The iteration order of the returned
480   * multiset matches that of the element set of {@code multiset1}, with repeated occurrences of the
481   * same element appearing consecutively.
482   *
483   * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different
484   * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are).
485   *
486   * @since 2.0
487   */
488  public static <E extends @Nullable Object> Multiset<E> intersection(
489      final Multiset<E> multiset1, final Multiset<?> multiset2) {
490    checkNotNull(multiset1);
491    checkNotNull(multiset2);
492
493    return new ViewMultiset<E>() {
494      @Override
495      public int count(@Nullable Object element) {
496        int count1 = multiset1.count(element);
497        return (count1 == 0) ? 0 : min(count1, multiset2.count(element));
498      }
499
500      @Override
501      Set<E> createElementSet() {
502        return Sets.intersection(multiset1.elementSet(), multiset2.elementSet());
503      }
504
505      @Override
506      Iterator<E> elementIterator() {
507        throw new AssertionError("should never be called");
508      }
509
510      @Override
511      Iterator<Entry<E>> entryIterator() {
512        final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator();
513        // TODO(lowasser): consider making the entries live views
514        return new AbstractIterator<Entry<E>>() {
515          @Override
516          protected @Nullable Entry<E> computeNext() {
517            while (iterator1.hasNext()) {
518              Entry<E> entry1 = iterator1.next();
519              E element = entry1.getElement();
520              int count = 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(@Nullable 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(@Nullable 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          protected @Nullable Entry<E> computeNext() {
588            if (iterator1.hasNext()) {
589              Entry<? extends E> entry1 = iterator1.next();
590              E element = entry1.getElement();
591              int count = entry1.getCount() + multiset2.count(element);
592              return immutableEntry(element, count);
593            }
594            while (iterator2.hasNext()) {
595              Entry<? extends E> entry2 = iterator2.next();
596              E element = entry2.getElement();
597              if (!multiset1.contains(element)) {
598                return immutableEntry(element, entry2.getCount());
599              }
600            }
601            return endOfData();
602          }
603        };
604      }
605    };
606  }
607
608  /**
609   * Returns an unmodifiable view of the difference of two multisets. In the returned multiset, the
610   * count of each element is the result of the <i>zero-truncated subtraction</i> of its count in
611   * the second multiset from its count in the first multiset, with elements that would have a count
612   * of 0 not included. The iteration order of the returned multiset matches that of the element set
613   * of {@code multiset1}, with repeated occurrences of the same element appearing consecutively.
614   *
615   * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different
616   * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are).
617   *
618   * @since 14.0
619   */
620  public static <E extends @Nullable Object> Multiset<E> difference(
621      final Multiset<E> multiset1, final Multiset<?> multiset2) {
622    checkNotNull(multiset1);
623    checkNotNull(multiset2);
624
625    // TODO(lowasser): consider making the entries live views
626    return new ViewMultiset<E>() {
627      @Override
628      public int count(@Nullable Object element) {
629        int count1 = multiset1.count(element);
630        return (count1 == 0) ? 0 : max(0, count1 - multiset2.count(element));
631      }
632
633      @Override
634      public void clear() {
635        throw new UnsupportedOperationException();
636      }
637
638      @Override
639      Iterator<E> elementIterator() {
640        final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator();
641        return new AbstractIterator<E>() {
642          @Override
643          protected @Nullable E computeNext() {
644            while (iterator1.hasNext()) {
645              Entry<E> entry1 = iterator1.next();
646              E element = entry1.getElement();
647              if (entry1.getCount() > multiset2.count(element)) {
648                return element;
649              }
650            }
651            return endOfData();
652          }
653        };
654      }
655
656      @Override
657      Iterator<Entry<E>> entryIterator() {
658        final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator();
659        return new AbstractIterator<Entry<E>>() {
660          @Override
661          protected @Nullable 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(@Nullable 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, @Nullable 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, (Multiset<? extends E>) 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(@Nullable 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(@Nullable 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(@Nullable Object o) {
1027      if (o instanceof Entry) {
1028        Entry<?> entry = (Entry<?>) o;
1029        if (entry.getCount() <= 0) {
1030          return false;
1031        }
1032        int count = multiset().count(entry.getElement());
1033        return count == entry.getCount();
1034      }
1035      return false;
1036    }
1037
1038    @Override
1039    public boolean remove(@Nullable Object object) {
1040      if (object instanceof Multiset.Entry) {
1041        Entry<?> entry = (Entry<?>) object;
1042        Object element = entry.getElement();
1043        int entryCount = entry.getCount();
1044        if (entryCount != 0) {
1045          // Safe as long as we never add a new entry, which we won't.
1046          // (Presumably it can still throw CCE/NPE but only if the underlying Multiset does.)
1047          @SuppressWarnings({"unchecked", "nullness"})
1048          Multiset<@Nullable Object> multiset = (Multiset<@Nullable Object>) multiset();
1049          return multiset.setCount(element, entryCount, 0);
1050        }
1051      }
1052      return false;
1053    }
1054
1055    @Override
1056    public void clear() {
1057      multiset().clear();
1058    }
1059  }
1060
1061  /** An implementation of {@link Multiset#iterator}. */
1062  static <E extends @Nullable Object> Iterator<E> iteratorImpl(Multiset<E> multiset) {
1063    return new MultisetIteratorImpl<>(multiset, multiset.entrySet().iterator());
1064  }
1065
1066  static final class MultisetIteratorImpl<E extends @Nullable Object> implements Iterator<E> {
1067    private final Multiset<E> multiset;
1068    private final Iterator<Entry<E>> entryIterator;
1069    private @Nullable Entry<E> currentEntry;
1070
1071    /** Count of subsequent elements equal to current element */
1072    private int laterCount;
1073
1074    /** Count of all elements equal to current element */
1075    private int totalCount;
1076
1077    private boolean canRemove;
1078
1079    MultisetIteratorImpl(Multiset<E> multiset, Iterator<Entry<E>> entryIterator) {
1080      this.multiset = multiset;
1081      this.entryIterator = entryIterator;
1082    }
1083
1084    @Override
1085    public boolean hasNext() {
1086      return laterCount > 0 || entryIterator.hasNext();
1087    }
1088
1089    @Override
1090    @ParametricNullness
1091    public E next() {
1092      if (!hasNext()) {
1093        throw new NoSuchElementException();
1094      }
1095      if (laterCount == 0) {
1096        currentEntry = entryIterator.next();
1097        totalCount = laterCount = currentEntry.getCount();
1098      }
1099      laterCount--;
1100      canRemove = true;
1101      /*
1102       * requireNonNull is safe because laterCount starts at 0, forcing us to initialize
1103       * currentEntry above. After that, we never clear it.
1104       */
1105      return requireNonNull(currentEntry).getElement();
1106    }
1107
1108    @Override
1109    public void remove() {
1110      checkRemove(canRemove);
1111      if (totalCount == 1) {
1112        entryIterator.remove();
1113      } else {
1114        /*
1115         * requireNonNull is safe because canRemove is set to true only after we initialize
1116         * currentEntry (which we never subsequently clear).
1117         */
1118        multiset.remove(requireNonNull(currentEntry).getElement());
1119      }
1120      totalCount--;
1121      canRemove = false;
1122    }
1123  }
1124
1125  static <E extends @Nullable Object> Spliterator<E> spliteratorImpl(Multiset<E> multiset) {
1126    Spliterator<Entry<E>> entrySpliterator = multiset.entrySet().spliterator();
1127    return CollectSpliterators.flatMap(
1128        entrySpliterator,
1129        (Entry<E> entry) -> Collections.nCopies(entry.getCount(), entry.getElement()).spliterator(),
1130        Spliterator.SIZED
1131            | (entrySpliterator.characteristics()
1132                & (Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.IMMUTABLE)),
1133        multiset.size());
1134  }
1135
1136  /** An implementation of {@link Multiset#size}. */
1137  static int linearTimeSizeImpl(Multiset<?> multiset) {
1138    long size = 0;
1139    for (Entry<?> entry : multiset.entrySet()) {
1140      size += entry.getCount();
1141    }
1142    return Ints.saturatedCast(size);
1143  }
1144
1145  /**
1146   * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order puts
1147   * the highest count first, with ties broken by the iteration order of the original multiset.
1148   *
1149   * @since 11.0
1150   */
1151  public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) {
1152    @SuppressWarnings("unchecked") // generics+arrays
1153    // TODO(cpovirk): Consider storing an Entry<?> instead of Entry<E>.
1154    Entry<E>[] entries = (Entry<E>[]) multiset.entrySet().toArray((Entry<E>[]) new Entry<?>[0]);
1155    Arrays.sort(entries, DecreasingCount.INSTANCE);
1156    return ImmutableMultiset.copyFromEntries(asList(entries));
1157  }
1158
1159  private static final class DecreasingCount implements Comparator<Entry<?>> {
1160    static final Comparator<Entry<?>> INSTANCE = new DecreasingCount();
1161
1162    @Override
1163    public int compare(Entry<?> entry1, Entry<?> entry2) {
1164      return entry2.getCount() - entry1.getCount(); // subtracting two nonnegative integers
1165    }
1166  }
1167
1168  /**
1169   * An {@link AbstractMultiset} with additional default implementations, some of them linear-time
1170   * implementations in terms of {@code elementSet} and {@code entrySet}.
1171   */
1172  private abstract static class ViewMultiset<E extends @Nullable Object>
1173      extends AbstractMultiset<E> {
1174    @Override
1175    public int size() {
1176      return linearTimeSizeImpl(this);
1177    }
1178
1179    @Override
1180    public void clear() {
1181      elementSet().clear();
1182    }
1183
1184    @Override
1185    public Iterator<E> iterator() {
1186      return iteratorImpl(this);
1187    }
1188
1189    @Override
1190    int distinctElements() {
1191      return elementSet().size();
1192    }
1193  }
1194}