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