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.InlineMe;
037import com.google.errorprone.annotations.concurrent.LazyInit;
038import java.io.Serializable;
039import java.util.Arrays;
040import java.util.Collection;
041import java.util.Collections;
042import java.util.Comparator;
043import java.util.Iterator;
044import java.util.NoSuchElementException;
045import java.util.Set;
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 33.2.0 (available since 22.0 in guava-jre)
084   */
085  @SuppressWarnings("Java7ApiChecker")
086  @IgnoreJRERequirement // Users will use this only if they're already using streams.
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  @InlineMe(
122      replacement = "checkNotNull(multiset)",
123      staticImports = "com.google.common.base.Preconditions.checkNotNull")
124  @Deprecated
125  public static <E> Multiset<E> unmodifiableMultiset(ImmutableMultiset<E> multiset) {
126    return checkNotNull(multiset);
127  }
128
129  static class UnmodifiableMultiset<E extends @Nullable Object> extends ForwardingMultiset<E>
130      implements Serializable {
131    final Multiset<? extends E> delegate;
132
133    UnmodifiableMultiset(Multiset<? extends E> delegate) {
134      this.delegate = delegate;
135    }
136
137    @SuppressWarnings("unchecked")
138    @Override
139    protected Multiset<E> delegate() {
140      // This is safe because all non-covariant methods are overridden
141      return (Multiset<E>) delegate;
142    }
143
144    @LazyInit transient @Nullable Set<E> elementSet;
145
146    Set<E> createElementSet() {
147      return Collections.<E>unmodifiableSet(delegate.elementSet());
148    }
149
150    @Override
151    public Set<E> elementSet() {
152      Set<E> es = elementSet;
153      return (es == null) ? elementSet = createElementSet() : es;
154    }
155
156    @LazyInit transient @Nullable Set<Multiset.Entry<E>> entrySet;
157
158    @SuppressWarnings("unchecked")
159    @Override
160    public Set<Multiset.Entry<E>> entrySet() {
161      Set<Multiset.Entry<E>> es = entrySet;
162      return (es == null)
163          // Safe because the returned set is made unmodifiable and Entry
164          // itself is readonly
165          ? entrySet = (Set) Collections.unmodifiableSet(delegate.entrySet())
166          : es;
167    }
168
169    @Override
170    public Iterator<E> iterator() {
171      return Iterators.<E>unmodifiableIterator(delegate.iterator());
172    }
173
174    @Override
175    public boolean add(@ParametricNullness E element) {
176      throw new UnsupportedOperationException();
177    }
178
179    @Override
180    public int add(@ParametricNullness E element, int occurrences) {
181      throw new UnsupportedOperationException();
182    }
183
184    @Override
185    public boolean addAll(Collection<? extends E> elementsToAdd) {
186      throw new UnsupportedOperationException();
187    }
188
189    @Override
190    public boolean remove(@Nullable Object element) {
191      throw new UnsupportedOperationException();
192    }
193
194    @Override
195    public int remove(@Nullable Object element, int occurrences) {
196      throw new UnsupportedOperationException();
197    }
198
199    @Override
200    public boolean removeAll(Collection<?> elementsToRemove) {
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    // It'd be nice if we could specialize for ImmutableMultiset here without also retaining
915    // its code when it's not in scope...
916    if (elements instanceof AbstractMapBasedMultiset) {
917      return addAllImpl(self, (AbstractMapBasedMultiset<? extends E>) elements);
918    } else if (elements.isEmpty()) {
919      return false;
920    } else {
921      for (Multiset.Entry<? extends E> entry : elements.entrySet()) {
922        self.add(entry.getElement(), entry.getCount());
923      }
924      return true;
925    }
926  }
927
928  /**
929   * A specialization of {@code addAllImpl} for when {@code elements} is an
930   * AbstractMapBasedMultiset.
931   */
932  private static <E extends @Nullable Object> boolean addAllImpl(
933      Multiset<E> self, AbstractMapBasedMultiset<? extends E> elements) {
934    if (elements.isEmpty()) {
935      return false;
936    }
937    elements.addTo(self);
938    return true;
939  }
940
941  /** An implementation of {@link Multiset#removeAll}. */
942  static boolean removeAllImpl(Multiset<?> self, Collection<?> elementsToRemove) {
943    Collection<?> collection =
944        (elementsToRemove instanceof Multiset)
945            ? ((Multiset<?>) elementsToRemove).elementSet()
946            : elementsToRemove;
947
948    return self.elementSet().removeAll(collection);
949  }
950
951  /** An implementation of {@link Multiset#retainAll}. */
952  static boolean retainAllImpl(Multiset<?> self, Collection<?> elementsToRetain) {
953    checkNotNull(elementsToRetain);
954    Collection<?> collection =
955        (elementsToRetain instanceof Multiset)
956            ? ((Multiset<?>) elementsToRetain).elementSet()
957            : elementsToRetain;
958
959    return self.elementSet().retainAll(collection);
960  }
961
962  /** An implementation of {@link Multiset#setCount(Object, int)}. */
963  static <E extends @Nullable Object> int setCountImpl(
964      Multiset<E> self, @ParametricNullness E element, int count) {
965    checkNonnegative(count, "count");
966
967    int oldCount = self.count(element);
968
969    int delta = count - oldCount;
970    if (delta > 0) {
971      self.add(element, delta);
972    } else if (delta < 0) {
973      self.remove(element, -delta);
974    }
975
976    return oldCount;
977  }
978
979  /** An implementation of {@link Multiset#setCount(Object, int, int)}. */
980  static <E extends @Nullable Object> boolean setCountImpl(
981      Multiset<E> self, @ParametricNullness E element, int oldCount, int newCount) {
982    checkNonnegative(oldCount, "oldCount");
983    checkNonnegative(newCount, "newCount");
984
985    if (self.count(element) == oldCount) {
986      self.setCount(element, newCount);
987      return true;
988    } else {
989      return false;
990    }
991  }
992
993  static <E extends @Nullable Object> Iterator<E> elementIterator(
994      Iterator<Entry<E>> entryIterator) {
995    return new TransformedIterator<Entry<E>, E>(entryIterator) {
996      @Override
997      @ParametricNullness
998      E transform(Entry<E> entry) {
999        return entry.getElement();
1000      }
1001    };
1002  }
1003
1004  abstract static class ElementSet<E extends @Nullable Object> extends Sets.ImprovedAbstractSet<E> {
1005    abstract Multiset<E> multiset();
1006
1007    @Override
1008    public void clear() {
1009      multiset().clear();
1010    }
1011
1012    @Override
1013    public boolean contains(@Nullable Object o) {
1014      return multiset().contains(o);
1015    }
1016
1017    @Override
1018    public boolean containsAll(Collection<?> c) {
1019      return multiset().containsAll(c);
1020    }
1021
1022    @Override
1023    public boolean isEmpty() {
1024      return multiset().isEmpty();
1025    }
1026
1027    @Override
1028    public abstract Iterator<E> iterator();
1029
1030    @Override
1031    public boolean remove(@Nullable Object o) {
1032      return multiset().remove(o, Integer.MAX_VALUE) > 0;
1033    }
1034
1035    @Override
1036    public int size() {
1037      return multiset().entrySet().size();
1038    }
1039  }
1040
1041  abstract static class EntrySet<E extends @Nullable Object>
1042      extends Sets.ImprovedAbstractSet<Entry<E>> {
1043    abstract Multiset<E> multiset();
1044
1045    @Override
1046    public boolean contains(@Nullable Object o) {
1047      if (o instanceof Entry) {
1048        Entry<?> entry = (Entry<?>) o;
1049        if (entry.getCount() <= 0) {
1050          return false;
1051        }
1052        int count = multiset().count(entry.getElement());
1053        return count == entry.getCount();
1054      }
1055      return false;
1056    }
1057
1058    @Override
1059    public boolean remove(@Nullable Object object) {
1060      if (object instanceof Multiset.Entry) {
1061        Entry<?> entry = (Entry<?>) object;
1062        Object element = entry.getElement();
1063        int entryCount = entry.getCount();
1064        if (entryCount != 0) {
1065          // Safe as long as we never add a new entry, which we won't.
1066          // (Presumably it can still throw CCE/NPE but only if the underlying Multiset does.)
1067          @SuppressWarnings({"unchecked", "nullness"})
1068          Multiset<@Nullable Object> multiset = (Multiset<@Nullable Object>) multiset();
1069          return multiset.setCount(element, entryCount, 0);
1070        }
1071      }
1072      return false;
1073    }
1074
1075    @Override
1076    public void clear() {
1077      multiset().clear();
1078    }
1079  }
1080
1081  /** An implementation of {@link Multiset#iterator}. */
1082  static <E extends @Nullable Object> Iterator<E> iteratorImpl(Multiset<E> multiset) {
1083    return new MultisetIteratorImpl<>(multiset, multiset.entrySet().iterator());
1084  }
1085
1086  static final class MultisetIteratorImpl<E extends @Nullable Object> implements Iterator<E> {
1087    private final Multiset<E> multiset;
1088    private final Iterator<Entry<E>> entryIterator;
1089    private @Nullable Entry<E> currentEntry;
1090
1091    /** Count of subsequent elements equal to current element */
1092    private int laterCount;
1093
1094    /** Count of all elements equal to current element */
1095    private int totalCount;
1096
1097    private boolean canRemove;
1098
1099    MultisetIteratorImpl(Multiset<E> multiset, Iterator<Entry<E>> entryIterator) {
1100      this.multiset = multiset;
1101      this.entryIterator = entryIterator;
1102    }
1103
1104    @Override
1105    public boolean hasNext() {
1106      return laterCount > 0 || entryIterator.hasNext();
1107    }
1108
1109    @Override
1110    @ParametricNullness
1111    public E next() {
1112      if (!hasNext()) {
1113        throw new NoSuchElementException();
1114      }
1115      if (laterCount == 0) {
1116        currentEntry = entryIterator.next();
1117        totalCount = laterCount = currentEntry.getCount();
1118      }
1119      laterCount--;
1120      canRemove = true;
1121      /*
1122       * requireNonNull is safe because laterCount starts at 0, forcing us to initialize
1123       * currentEntry above. After that, we never clear it.
1124       */
1125      return requireNonNull(currentEntry).getElement();
1126    }
1127
1128    @Override
1129    public void remove() {
1130      checkRemove(canRemove);
1131      if (totalCount == 1) {
1132        entryIterator.remove();
1133      } else {
1134        /*
1135         * requireNonNull is safe because canRemove is set to true only after we initialize
1136         * currentEntry (which we never subsequently clear).
1137         */
1138        multiset.remove(requireNonNull(currentEntry).getElement());
1139      }
1140      totalCount--;
1141      canRemove = false;
1142    }
1143  }
1144
1145  /** An implementation of {@link Multiset#size}. */
1146  static int linearTimeSizeImpl(Multiset<?> multiset) {
1147    long size = 0;
1148    for (Entry<?> entry : multiset.entrySet()) {
1149      size += entry.getCount();
1150    }
1151    return Ints.saturatedCast(size);
1152  }
1153
1154  /**
1155   * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order puts
1156   * the highest count first, with ties broken by the iteration order of the original multiset.
1157   *
1158   * @since 11.0
1159   */
1160  public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) {
1161    @SuppressWarnings("unchecked") // generics+arrays
1162    // TODO(cpovirk): Consider storing an Entry<?> instead of Entry<E>.
1163    Entry<E>[] entries = (Entry<E>[]) multiset.entrySet().toArray((Entry<E>[]) new Entry<?>[0]);
1164    Arrays.sort(entries, DecreasingCount.INSTANCE);
1165    return ImmutableMultiset.copyFromEntries(asList(entries));
1166  }
1167
1168  private static final class DecreasingCount implements Comparator<Entry<?>> {
1169    static final Comparator<Entry<?>> 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}