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