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