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 @NullableDecl 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 @NullableDecl 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 ViewMultiset<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 Iterator<E> elementIterator() { 301 throw new AssertionError("should never be called"); 302 } 303 304 @Override 305 Set<Entry<E>> createEntrySet() { 306 return Sets.filter( 307 unfiltered.entrySet(), 308 new Predicate<Entry<E>>() { 309 @Override 310 public boolean apply(Entry<E> entry) { 311 return predicate.apply(entry.getElement()); 312 } 313 }); 314 } 315 316 @Override 317 Iterator<Entry<E>> entryIterator() { 318 throw new AssertionError("should never be called"); 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 350 /** 351 * Returns the expected number of distinct elements given the specified elements. The number of 352 * distinct elements is only computed if {@code elements} is an instance of {@code Multiset}; 353 * otherwise the default value of 11 is returned. 354 */ 355 static int inferDistinctElements(Iterable<?> elements) { 356 if (elements instanceof Multiset) { 357 return ((Multiset<?>) elements).elementSet().size(); 358 } 359 return 11; // initial capacity will be rounded up to 16 360 } 361 362 /** 363 * Returns an unmodifiable view of the union of two multisets. In the returned multiset, the count 364 * of each element is the <i>maximum</i> of its counts in the two backing multisets. The iteration 365 * order of the returned multiset matches that of the element set of {@code multiset1} followed by 366 * the members of the element set of {@code multiset2} that are not contained in {@code 367 * multiset1}, with repeated occurrences of the same element appearing consecutively. 368 * 369 * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different 370 * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are). 371 * 372 * @since 14.0 373 */ 374 @Beta 375 public static <E> Multiset<E> union( 376 final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) { 377 checkNotNull(multiset1); 378 checkNotNull(multiset2); 379 380 return new ViewMultiset<E>() { 381 @Override 382 public boolean contains(@NullableDecl Object element) { 383 return multiset1.contains(element) || multiset2.contains(element); 384 } 385 386 @Override 387 public boolean isEmpty() { 388 return multiset1.isEmpty() && multiset2.isEmpty(); 389 } 390 391 @Override 392 public int count(Object element) { 393 return Math.max(multiset1.count(element), multiset2.count(element)); 394 } 395 396 @Override 397 Set<E> createElementSet() { 398 return Sets.union(multiset1.elementSet(), multiset2.elementSet()); 399 } 400 401 @Override 402 Iterator<E> elementIterator() { 403 throw new AssertionError("should never be called"); 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 } 433 434 /** 435 * Returns an unmodifiable view of the intersection of two multisets. In the returned multiset, 436 * the count of each element is the <i>minimum</i> of its counts in the two backing multisets, 437 * with elements that would have a count of 0 not included. The iteration order of the returned 438 * multiset matches that of the element set of {@code multiset1}, with repeated occurrences of the 439 * same element appearing consecutively. 440 * 441 * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different 442 * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are). 443 * 444 * @since 2.0 445 */ 446 public static <E> Multiset<E> intersection( 447 final Multiset<E> multiset1, final Multiset<?> multiset2) { 448 checkNotNull(multiset1); 449 checkNotNull(multiset2); 450 451 return new ViewMultiset<E>() { 452 @Override 453 public int count(Object element) { 454 int count1 = multiset1.count(element); 455 return (count1 == 0) ? 0 : Math.min(count1, multiset2.count(element)); 456 } 457 458 @Override 459 Set<E> createElementSet() { 460 return Sets.intersection(multiset1.elementSet(), multiset2.elementSet()); 461 } 462 463 @Override 464 Iterator<E> elementIterator() { 465 throw new AssertionError("should never be called"); 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 } 489 490 /** 491 * Returns an unmodifiable view of the sum of two multisets. In the returned multiset, the count 492 * of each element is the <i>sum</i> of its counts in the two backing multisets. The iteration 493 * order of the returned multiset matches that of the element set of {@code multiset1} followed by 494 * the members of the element set of {@code multiset2} that are not contained in {@code 495 * multiset1}, with repeated occurrences of the same element appearing consecutively. 496 * 497 * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different 498 * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are). 499 * 500 * @since 14.0 501 */ 502 @Beta 503 public static <E> Multiset<E> sum( 504 final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) { 505 checkNotNull(multiset1); 506 checkNotNull(multiset2); 507 508 // TODO(lowasser): consider making the entries live views 509 return new ViewMultiset<E>() { 510 @Override 511 public boolean contains(@NullableDecl Object element) { 512 return multiset1.contains(element) || multiset2.contains(element); 513 } 514 515 @Override 516 public boolean isEmpty() { 517 return multiset1.isEmpty() && multiset2.isEmpty(); 518 } 519 520 @Override 521 public int size() { 522 return IntMath.saturatedAdd(multiset1.size(), multiset2.size()); 523 } 524 525 @Override 526 public int count(Object element) { 527 return multiset1.count(element) + multiset2.count(element); 528 } 529 530 @Override 531 Set<E> createElementSet() { 532 return Sets.union(multiset1.elementSet(), multiset2.elementSet()); 533 } 534 535 @Override 536 Iterator<E> elementIterator() { 537 throw new AssertionError("should never be called"); 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 } 566 567 /** 568 * Returns an unmodifiable view of the difference of two multisets. In the returned multiset, the 569 * count of each element is the result of the <i>zero-truncated subtraction</i> of its count in 570 * the second multiset from its count in the first multiset, with elements that would have a count 571 * of 0 not included. The iteration order of the returned multiset matches that of the element set 572 * of {@code multiset1}, with repeated occurrences of the same element appearing consecutively. 573 * 574 * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different 575 * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are). 576 * 577 * @since 14.0 578 */ 579 @Beta 580 public static <E> Multiset<E> difference( 581 final Multiset<E> multiset1, final Multiset<?> multiset2) { 582 checkNotNull(multiset1); 583 checkNotNull(multiset2); 584 585 // TODO(lowasser): consider making the entries live views 586 return new ViewMultiset<E>() { 587 @Override 588 public int count(@NullableDecl Object element) { 589 int count1 = multiset1.count(element); 590 return (count1 == 0) ? 0 : Math.max(0, count1 - multiset2.count(element)); 591 } 592 593 @Override 594 public void clear() { 595 throw new UnsupportedOperationException(); 596 } 597 598 @Override 599 Iterator<E> elementIterator() { 600 final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator(); 601 return new AbstractIterator<E>() { 602 @Override 603 protected E computeNext() { 604 while (iterator1.hasNext()) { 605 Entry<E> entry1 = iterator1.next(); 606 E element = entry1.getElement(); 607 if (entry1.getCount() > multiset2.count(element)) { 608 return element; 609 } 610 } 611 return endOfData(); 612 } 613 }; 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) <= superMultiset.count(o)} for all {@code 644 * o}. 645 * 646 * @since 10.0 647 */ 648 @CanIgnoreReturnValue 649 public static boolean containsOccurrences(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 {@code e} is at most {@code 663 * multisetToRetain.count(e)}. 664 * 665 * <p>To be precise, {@code multisetToModify.count(e)} is set to {@code 666 * Math.min(multisetToModify.count(e), multisetToRetain.count(e))}. This is similar to {@link 667 * #intersection(Multiset, Multiset) intersection} {@code (multisetToModify, multisetToRetain)}, 668 * but mutates {@code multisetToModify} instead of returning a view. 669 * 670 * <p>In contrast, {@code multisetToModify.retainAll(multisetToRetain)} keeps all occurrences of 671 * elements that appear at all in {@code multisetToRetain}, and deletes all occurrences of all 672 * other elements. 673 * 674 * @return {@code true} if {@code multisetToModify} was changed as a result of this operation 675 * @since 10.0 676 */ 677 @CanIgnoreReturnValue 678 public static boolean retainOccurrences( 679 Multiset<?> multisetToModify, Multiset<?> multisetToRetain) { 680 return retainOccurrencesImpl(multisetToModify, multisetToRetain); 681 } 682 683 /** Delegate implementation which cares about the element type. */ 684 private static <E> boolean retainOccurrencesImpl( 685 Multiset<E> multisetToModify, Multiset<?> occurrencesToRetain) { 686 checkNotNull(multisetToModify); 687 checkNotNull(occurrencesToRetain); 688 // Avoiding ConcurrentModificationExceptions is tricky. 689 Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator(); 690 boolean changed = false; 691 while (entryIterator.hasNext()) { 692 Entry<E> entry = entryIterator.next(); 693 int retainCount = occurrencesToRetain.count(entry.getElement()); 694 if (retainCount == 0) { 695 entryIterator.remove(); 696 changed = true; 697 } else if (retainCount < entry.getCount()) { 698 multisetToModify.setCount(entry.getElement(), retainCount); 699 changed = true; 700 } 701 } 702 return changed; 703 } 704 705 /** 706 * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, removes one 707 * occurrence of {@code e} in {@code multisetToModify}. 708 * 709 * <p>Equivalently, this method modifies {@code multisetToModify} so that {@code 710 * multisetToModify.count(e)} is set to {@code Math.max(0, multisetToModify.count(e) - 711 * Iterables.frequency(occurrencesToRemove, e))}. 712 * 713 * <p>This is <i>not</i> the same as {@code multisetToModify.} {@link Multiset#removeAll 714 * removeAll}{@code (occurrencesToRemove)}, which removes all occurrences of elements that appear 715 * in {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent to, albeit 716 * sometimes more efficient than, the following: 717 * 718 * <pre>{@code 719 * for (E e : occurrencesToRemove) { 720 * multisetToModify.remove(e); 721 * } 722 * }</pre> 723 * 724 * @return {@code true} if {@code multisetToModify} was changed as a result of this operation 725 * @since 18.0 (present in 10.0 with a requirement that the second parameter be a {@code 726 * Multiset}) 727 */ 728 @CanIgnoreReturnValue 729 public static boolean removeOccurrences( 730 Multiset<?> multisetToModify, Iterable<?> occurrencesToRemove) { 731 if (occurrencesToRemove instanceof Multiset) { 732 return removeOccurrences(multisetToModify, (Multiset<?>) occurrencesToRemove); 733 } else { 734 checkNotNull(multisetToModify); 735 checkNotNull(occurrencesToRemove); 736 boolean changed = false; 737 for (Object o : occurrencesToRemove) { 738 changed |= multisetToModify.remove(o); 739 } 740 return changed; 741 } 742 } 743 744 /** 745 * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, removes one 746 * occurrence of {@code e} in {@code multisetToModify}. 747 * 748 * <p>Equivalently, this method modifies {@code multisetToModify} so that {@code 749 * multisetToModify.count(e)} is set to {@code Math.max(0, multisetToModify.count(e) - 750 * occurrencesToRemove.count(e))}. 751 * 752 * <p>This is <i>not</i> the same as {@code multisetToModify.} {@link Multiset#removeAll 753 * removeAll}{@code (occurrencesToRemove)}, which removes all occurrences of elements that appear 754 * in {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent to, albeit 755 * sometimes more efficient than, the following: 756 * 757 * <pre>{@code 758 * for (E e : occurrencesToRemove) { 759 * multisetToModify.remove(e); 760 * } 761 * }</pre> 762 * 763 * @return {@code true} if {@code multisetToModify} was changed as a result of this operation 764 * @since 10.0 (missing in 18.0 when only the overload taking an {@code Iterable} was present) 765 */ 766 @CanIgnoreReturnValue 767 public static boolean removeOccurrences( 768 Multiset<?> multisetToModify, Multiset<?> occurrencesToRemove) { 769 checkNotNull(multisetToModify); 770 checkNotNull(occurrencesToRemove); 771 772 boolean changed = false; 773 Iterator<? extends Entry<?>> entryIterator = multisetToModify.entrySet().iterator(); 774 while (entryIterator.hasNext()) { 775 Entry<?> entry = entryIterator.next(); 776 int removeCount = occurrencesToRemove.count(entry.getElement()); 777 if (removeCount >= entry.getCount()) { 778 entryIterator.remove(); 779 changed = true; 780 } else if (removeCount > 0) { 781 multisetToModify.remove(entry.getElement(), removeCount); 782 changed = true; 783 } 784 } 785 return changed; 786 } 787 788 /** 789 * Implementation of the {@code equals}, {@code hashCode}, and {@code toString} methods of {@link 790 * Multiset.Entry}. 791 */ 792 abstract static class AbstractEntry<E> implements Multiset.Entry<E> { 793 /** 794 * Indicates whether an object equals this entry, following the behavior specified in {@link 795 * Multiset.Entry#equals}. 796 */ 797 @Override 798 public boolean equals(@NullableDecl Object object) { 799 if (object instanceof Multiset.Entry) { 800 Multiset.Entry<?> that = (Multiset.Entry<?>) object; 801 return this.getCount() == that.getCount() 802 && Objects.equal(this.getElement(), that.getElement()); 803 } 804 return false; 805 } 806 807 /** 808 * Return this entry's hash code, following the behavior specified in {@link 809 * Multiset.Entry#hashCode}. 810 */ 811 @Override 812 public int hashCode() { 813 E e = getElement(); 814 return ((e == null) ? 0 : e.hashCode()) ^ getCount(); 815 } 816 817 /** 818 * Returns a string representation of this multiset entry. The string representation consists of 819 * the associated element if the associated count is one, and otherwise the associated element 820 * followed by the characters " x " (space, x and space) followed by the count. Elements and 821 * counts are converted to strings as by {@code String.valueOf}. 822 */ 823 @Override 824 public String toString() { 825 String text = String.valueOf(getElement()); 826 int n = getCount(); 827 return (n == 1) ? text : (text + " x " + n); 828 } 829 } 830 831 /** An implementation of {@link Multiset#equals}. */ 832 static boolean equalsImpl(Multiset<?> multiset, @NullableDecl Object object) { 833 if (object == multiset) { 834 return true; 835 } 836 if (object instanceof Multiset) { 837 Multiset<?> that = (Multiset<?>) object; 838 /* 839 * We can't simply check whether the entry sets are equal, since that 840 * approach fails when a TreeMultiset has a comparator that returns 0 841 * when passed unequal elements. 842 */ 843 844 if (multiset.size() != that.size() || multiset.entrySet().size() != that.entrySet().size()) { 845 return false; 846 } 847 for (Entry<?> entry : that.entrySet()) { 848 if (multiset.count(entry.getElement()) != entry.getCount()) { 849 return false; 850 } 851 } 852 return true; 853 } 854 return false; 855 } 856 857 /** An implementation of {@link Multiset#addAll}. */ 858 static <E> boolean addAllImpl(Multiset<E> self, Collection<? extends E> elements) { 859 checkNotNull(self); 860 checkNotNull(elements); 861 if (elements instanceof Multiset) { 862 return addAllImpl(self, cast(elements)); 863 } else if (elements.isEmpty()) { 864 return false; 865 } else { 866 return Iterators.addAll(self, elements.iterator()); 867 } 868 } 869 870 /** A specialization of {@code addAllImpl} for when {@code elements} is itself a Multiset. */ 871 private static <E> boolean addAllImpl(Multiset<E> self, Multiset<? extends E> elements) { 872 // It'd be nice if we could specialize for ImmutableMultiset here without also retaining 873 // its code when it's not in scope... 874 if (elements instanceof AbstractMapBasedMultiset) { 875 return addAllImpl(self, (AbstractMapBasedMultiset<? extends E>) elements); 876 } else if (elements.isEmpty()) { 877 return false; 878 } else { 879 for (Multiset.Entry<? extends E> entry : elements.entrySet()) { 880 self.add(entry.getElement(), entry.getCount()); 881 } 882 return true; 883 } 884 } 885 886 /** 887 * A specialization of {@code addAllImpl} for when {@code elements} is an 888 * AbstractMapBasedMultiset. 889 */ 890 private static <E> boolean addAllImpl( 891 Multiset<E> self, AbstractMapBasedMultiset<? extends E> elements) { 892 if (elements.isEmpty()) { 893 return false; 894 } 895 elements.addTo(self); 896 return true; 897 } 898 899 /** An implementation of {@link Multiset#removeAll}. */ 900 static boolean removeAllImpl(Multiset<?> self, Collection<?> elementsToRemove) { 901 Collection<?> collection = 902 (elementsToRemove instanceof Multiset) 903 ? ((Multiset<?>) elementsToRemove).elementSet() 904 : elementsToRemove; 905 906 return self.elementSet().removeAll(collection); 907 } 908 909 /** An implementation of {@link Multiset#retainAll}. */ 910 static boolean retainAllImpl(Multiset<?> self, Collection<?> elementsToRetain) { 911 checkNotNull(elementsToRetain); 912 Collection<?> collection = 913 (elementsToRetain instanceof Multiset) 914 ? ((Multiset<?>) elementsToRetain).elementSet() 915 : elementsToRetain; 916 917 return self.elementSet().retainAll(collection); 918 } 919 920 /** An implementation of {@link Multiset#setCount(Object, int)}. */ 921 static <E> int setCountImpl(Multiset<E> self, E element, int count) { 922 checkNonnegative(count, "count"); 923 924 int oldCount = self.count(element); 925 926 int delta = count - oldCount; 927 if (delta > 0) { 928 self.add(element, delta); 929 } else if (delta < 0) { 930 self.remove(element, -delta); 931 } 932 933 return oldCount; 934 } 935 936 /** An implementation of {@link Multiset#setCount(Object, int, int)}. */ 937 static <E> boolean setCountImpl(Multiset<E> self, E element, int oldCount, int newCount) { 938 checkNonnegative(oldCount, "oldCount"); 939 checkNonnegative(newCount, "newCount"); 940 941 if (self.count(element) == oldCount) { 942 self.setCount(element, newCount); 943 return true; 944 } else { 945 return false; 946 } 947 } 948 949 static <E> Iterator<E> elementIterator(Iterator<Entry<E>> entryIterator) { 950 return new TransformedIterator<Entry<E>, E>(entryIterator) { 951 @Override 952 E transform(Entry<E> entry) { 953 return entry.getElement(); 954 } 955 }; 956 } 957 958 abstract static class ElementSet<E> extends Sets.ImprovedAbstractSet<E> { 959 abstract Multiset<E> multiset(); 960 961 @Override 962 public void clear() { 963 multiset().clear(); 964 } 965 966 @Override 967 public boolean contains(Object o) { 968 return multiset().contains(o); 969 } 970 971 @Override 972 public boolean containsAll(Collection<?> c) { 973 return multiset().containsAll(c); 974 } 975 976 @Override 977 public boolean isEmpty() { 978 return multiset().isEmpty(); 979 } 980 981 @Override 982 public abstract Iterator<E> iterator(); 983 984 @Override 985 public boolean remove(Object o) { 986 return multiset().remove(o, Integer.MAX_VALUE) > 0; 987 } 988 989 @Override 990 public int size() { 991 return multiset().entrySet().size(); 992 } 993 } 994 995 abstract static class EntrySet<E> extends Sets.ImprovedAbstractSet<Entry<E>> { 996 abstract Multiset<E> multiset(); 997 998 @Override 999 public boolean contains(@NullableDecl Object o) { 1000 if (o instanceof Entry) { 1001 /* 1002 * The GWT compiler wrongly issues a warning here. 1003 */ 1004 @SuppressWarnings("cast") 1005 Entry<?> entry = (Entry<?>) o; 1006 if (entry.getCount() <= 0) { 1007 return false; 1008 } 1009 int count = multiset().count(entry.getElement()); 1010 return count == entry.getCount(); 1011 } 1012 return false; 1013 } 1014 1015 // GWT compiler warning; see contains(). 1016 @SuppressWarnings("cast") 1017 @Override 1018 public boolean remove(Object object) { 1019 if (object instanceof Multiset.Entry) { 1020 Entry<?> entry = (Entry<?>) object; 1021 Object element = entry.getElement(); 1022 int entryCount = entry.getCount(); 1023 if (entryCount != 0) { 1024 // Safe as long as we never add a new entry, which we won't. 1025 @SuppressWarnings("unchecked") 1026 Multiset<Object> multiset = (Multiset<Object>) multiset(); 1027 return multiset.setCount(element, entryCount, 0); 1028 } 1029 } 1030 return false; 1031 } 1032 1033 @Override 1034 public void clear() { 1035 multiset().clear(); 1036 } 1037 } 1038 1039 /** An implementation of {@link Multiset#iterator}. */ 1040 static <E> Iterator<E> iteratorImpl(Multiset<E> multiset) { 1041 return new MultisetIteratorImpl<E>(multiset, multiset.entrySet().iterator()); 1042 } 1043 1044 static final class MultisetIteratorImpl<E> implements Iterator<E> { 1045 private final Multiset<E> multiset; 1046 private final Iterator<Entry<E>> entryIterator; 1047 @NullableDecl private Entry<E> currentEntry; 1048 1049 /** Count of subsequent elements equal to current element */ 1050 private int laterCount; 1051 1052 /** Count of all elements equal to current element */ 1053 private int totalCount; 1054 1055 private boolean canRemove; 1056 1057 MultisetIteratorImpl(Multiset<E> multiset, Iterator<Entry<E>> entryIterator) { 1058 this.multiset = multiset; 1059 this.entryIterator = entryIterator; 1060 } 1061 1062 @Override 1063 public boolean hasNext() { 1064 return laterCount > 0 || entryIterator.hasNext(); 1065 } 1066 1067 @Override 1068 public E next() { 1069 if (!hasNext()) { 1070 throw new NoSuchElementException(); 1071 } 1072 if (laterCount == 0) { 1073 currentEntry = entryIterator.next(); 1074 totalCount = laterCount = currentEntry.getCount(); 1075 } 1076 laterCount--; 1077 canRemove = true; 1078 return currentEntry.getElement(); 1079 } 1080 1081 @Override 1082 public void remove() { 1083 checkRemove(canRemove); 1084 if (totalCount == 1) { 1085 entryIterator.remove(); 1086 } else { 1087 multiset.remove(currentEntry.getElement()); 1088 } 1089 totalCount--; 1090 canRemove = false; 1091 } 1092 } 1093 1094 /** An implementation of {@link Multiset#size}. */ 1095 static int linearTimeSizeImpl(Multiset<?> multiset) { 1096 long size = 0; 1097 for (Entry<?> entry : multiset.entrySet()) { 1098 size += entry.getCount(); 1099 } 1100 return Ints.saturatedCast(size); 1101 } 1102 1103 /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ 1104 static <T> Multiset<T> cast(Iterable<T> iterable) { 1105 return (Multiset<T>) iterable; 1106 } 1107 1108 /** 1109 * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order is 1110 * highest count first, with ties broken by the iteration order of the original multiset. 1111 * 1112 * @since 11.0 1113 */ 1114 @Beta 1115 public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) { 1116 Entry<E>[] entries = (Entry<E>[]) multiset.entrySet().toArray(new Entry[0]); 1117 Arrays.sort(entries, DecreasingCount.INSTANCE); 1118 return ImmutableMultiset.copyFromEntries(Arrays.asList(entries)); 1119 } 1120 1121 private static final class DecreasingCount implements Comparator<Entry<?>> { 1122 static final DecreasingCount INSTANCE = new DecreasingCount(); 1123 1124 @Override 1125 public int compare(Entry<?> entry1, Entry<?> entry2) { 1126 return entry2.getCount() - entry1.getCount(); // subtracting two nonnegative integers 1127 } 1128 } 1129 1130 /** 1131 * An {@link AbstractMultiset} with additional default implementations, some of them linear-time 1132 * implementations in terms of {@code elementSet} and {@code entrySet}. 1133 */ 1134 private abstract static class ViewMultiset<E> extends AbstractMultiset<E> { 1135 @Override 1136 public int size() { 1137 return linearTimeSizeImpl(this); 1138 } 1139 1140 @Override 1141 public void clear() { 1142 elementSet().clear(); 1143 } 1144 1145 @Override 1146 public Iterator<E> iterator() { 1147 return iteratorImpl(this); 1148 } 1149 1150 @Override 1151 int distinctElements() { 1152 return elementSet().size(); 1153 } 1154 } 1155}