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