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