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