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