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