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