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