001/* 002 * Copyright (C) 2008 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 java.util.Objects.requireNonNull; 023 024import com.google.common.annotations.GwtCompatible; 025import com.google.common.base.Function; 026import com.google.common.base.Predicate; 027import com.google.common.base.Predicates; 028import com.google.common.math.IntMath; 029import com.google.common.primitives.Ints; 030import java.util.AbstractCollection; 031import java.util.ArrayList; 032import java.util.Arrays; 033import java.util.Collection; 034import java.util.Collections; 035import java.util.Comparator; 036import java.util.Iterator; 037import java.util.List; 038import java.util.Spliterator; 039import java.util.function.Consumer; 040import javax.annotation.CheckForNull; 041import org.checkerframework.checker.nullness.qual.Nullable; 042 043/** 044 * Provides static methods for working with {@code Collection} instances. 045 * 046 * <p><b>Java 8+ users:</b> several common uses for this class are now more comprehensively 047 * addressed by the new {@link java.util.stream.Stream} library. Read the method documentation below 048 * for comparisons. These methods are not being deprecated, but we gently encourage you to migrate 049 * to streams. 050 * 051 * @author Chris Povirk 052 * @author Mike Bostock 053 * @author Jared Levy 054 * @since 2.0 055 */ 056@GwtCompatible 057@ElementTypesAreNonnullByDefault 058public final class Collections2 { 059 private Collections2() {} 060 061 /** 062 * Returns the elements of {@code unfiltered} that satisfy a predicate. The returned collection is 063 * a live view of {@code unfiltered}; changes to one affect the other. 064 * 065 * <p>The resulting collection's iterator does not support {@code remove()}, but all other 066 * collection methods are supported. When given an element that doesn't satisfy the predicate, the 067 * collection's {@code add()} and {@code addAll()} methods throw an {@link 068 * IllegalArgumentException}. When methods such as {@code removeAll()} and {@code clear()} are 069 * called on the filtered collection, only elements that satisfy the filter will be removed from 070 * the underlying collection. 071 * 072 * <p>The returned collection isn't threadsafe or serializable, even if {@code unfiltered} is. 073 * 074 * <p>Many of the filtered collection's methods, such as {@code size()}, iterate across every 075 * element in the underlying collection and determine which elements satisfy the filter. When a 076 * live view is <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, 077 * predicate)} and use the copy. 078 * 079 * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at 080 * {@link Predicate#apply}. Do not provide a predicate such as {@code 081 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link 082 * Iterables#filter(Iterable, Class)} for related functionality.) 083 * 084 * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#filter Stream.filter}. 085 */ 086 // TODO(kevinb): how can we omit that Iterables link when building gwt 087 // javadoc? 088 public static <E extends @Nullable Object> Collection<E> filter( 089 Collection<E> unfiltered, Predicate<? super E> predicate) { 090 if (unfiltered instanceof FilteredCollection) { 091 // Support clear(), removeAll(), and retainAll() when filtering a filtered 092 // collection. 093 return ((FilteredCollection<E>) unfiltered).createCombined(predicate); 094 } 095 096 return new FilteredCollection<>(checkNotNull(unfiltered), checkNotNull(predicate)); 097 } 098 099 /** 100 * Delegates to {@link Collection#contains}. Returns {@code false} if the {@code contains} method 101 * throws a {@code ClassCastException} or {@code NullPointerException}. 102 */ 103 static boolean safeContains(Collection<?> collection, @CheckForNull Object object) { 104 checkNotNull(collection); 105 try { 106 return collection.contains(object); 107 } catch (ClassCastException | NullPointerException e) { 108 return false; 109 } 110 } 111 112 /** 113 * Delegates to {@link Collection#remove}. Returns {@code false} if the {@code remove} method 114 * throws a {@code ClassCastException} or {@code NullPointerException}. 115 */ 116 static boolean safeRemove(Collection<?> collection, @CheckForNull Object object) { 117 checkNotNull(collection); 118 try { 119 return collection.remove(object); 120 } catch (ClassCastException | NullPointerException e) { 121 return false; 122 } 123 } 124 125 static class FilteredCollection<E extends @Nullable Object> extends AbstractCollection<E> { 126 final Collection<E> unfiltered; 127 final Predicate<? super E> predicate; 128 129 FilteredCollection(Collection<E> unfiltered, Predicate<? super E> predicate) { 130 this.unfiltered = unfiltered; 131 this.predicate = predicate; 132 } 133 134 FilteredCollection<E> createCombined(Predicate<? super E> newPredicate) { 135 return new FilteredCollection<>(unfiltered, Predicates.and(predicate, newPredicate)); 136 } 137 138 @Override 139 public boolean add(@ParametricNullness E element) { 140 checkArgument(predicate.apply(element)); 141 return unfiltered.add(element); 142 } 143 144 @Override 145 public boolean addAll(Collection<? extends E> collection) { 146 for (E element : collection) { 147 checkArgument(predicate.apply(element)); 148 } 149 return unfiltered.addAll(collection); 150 } 151 152 @Override 153 public void clear() { 154 Iterables.removeIf(unfiltered, predicate); 155 } 156 157 @Override 158 public boolean contains(@CheckForNull Object element) { 159 if (safeContains(unfiltered, element)) { 160 @SuppressWarnings("unchecked") // element is in unfiltered, so it must be an E 161 E e = (E) element; 162 return predicate.apply(e); 163 } 164 return false; 165 } 166 167 @Override 168 public boolean containsAll(Collection<?> collection) { 169 return containsAllImpl(this, collection); 170 } 171 172 @Override 173 public boolean isEmpty() { 174 return !Iterables.any(unfiltered, predicate); 175 } 176 177 @Override 178 public Iterator<E> iterator() { 179 return Iterators.filter(unfiltered.iterator(), predicate); 180 } 181 182 @Override 183 public Spliterator<E> spliterator() { 184 return CollectSpliterators.filter(unfiltered.spliterator(), predicate); 185 } 186 187 @Override 188 public void forEach(Consumer<? super E> action) { 189 checkNotNull(action); 190 unfiltered.forEach( 191 (E e) -> { 192 if (predicate.test(e)) { 193 action.accept(e); 194 } 195 }); 196 } 197 198 @Override 199 public boolean remove(@CheckForNull Object element) { 200 return contains(element) && unfiltered.remove(element); 201 } 202 203 @Override 204 public boolean removeAll(final Collection<?> collection) { 205 return removeIf(collection::contains); 206 } 207 208 @Override 209 public boolean retainAll(final Collection<?> collection) { 210 return removeIf(element -> !collection.contains(element)); 211 } 212 213 @Override 214 public boolean removeIf(java.util.function.Predicate<? super E> filter) { 215 checkNotNull(filter); 216 return unfiltered.removeIf(element -> predicate.apply(element) && filter.test(element)); 217 } 218 219 @Override 220 public int size() { 221 int size = 0; 222 for (E e : unfiltered) { 223 if (predicate.apply(e)) { 224 size++; 225 } 226 } 227 return size; 228 } 229 230 @Override 231 public @Nullable Object[] toArray() { 232 // creating an ArrayList so filtering happens once 233 return Lists.newArrayList(iterator()).toArray(); 234 } 235 236 @Override 237 @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations 238 public <T extends @Nullable Object> T[] toArray(T[] array) { 239 return Lists.newArrayList(iterator()).toArray(array); 240 } 241 } 242 243 /** 244 * Returns a collection that applies {@code function} to each element of {@code fromCollection}. 245 * The returned collection is a live view of {@code fromCollection}; changes to one affect the 246 * other. 247 * 248 * <p>The returned collection's {@code add()} and {@code addAll()} methods throw an {@link 249 * UnsupportedOperationException}. All other collection methods are supported, as long as {@code 250 * fromCollection} supports them. 251 * 252 * <p>The returned collection isn't threadsafe or serializable, even if {@code fromCollection} is. 253 * 254 * <p>When a live view is <i>not</i> needed, it may be faster to copy the transformed collection 255 * and use the copy. 256 * 257 * <p>If the input {@code Collection} is known to be a {@code List}, consider {@link 258 * Lists#transform}. If only an {@code Iterable} is available, use {@link Iterables#transform}. 259 * 260 * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#map Stream.map}. 261 */ 262 public static <F extends @Nullable Object, T extends @Nullable Object> Collection<T> transform( 263 Collection<F> fromCollection, Function<? super F, T> function) { 264 return new TransformedCollection<>(fromCollection, function); 265 } 266 267 static class TransformedCollection<F extends @Nullable Object, T extends @Nullable Object> 268 extends AbstractCollection<T> { 269 final Collection<F> fromCollection; 270 final Function<? super F, ? extends T> function; 271 272 TransformedCollection(Collection<F> fromCollection, Function<? super F, ? extends T> function) { 273 this.fromCollection = checkNotNull(fromCollection); 274 this.function = checkNotNull(function); 275 } 276 277 @Override 278 public void clear() { 279 fromCollection.clear(); 280 } 281 282 @Override 283 public boolean isEmpty() { 284 return fromCollection.isEmpty(); 285 } 286 287 @Override 288 public Iterator<T> iterator() { 289 return Iterators.transform(fromCollection.iterator(), function); 290 } 291 292 @Override 293 public Spliterator<T> spliterator() { 294 return CollectSpliterators.map(fromCollection.spliterator(), function); 295 } 296 297 @Override 298 public void forEach(Consumer<? super T> action) { 299 checkNotNull(action); 300 fromCollection.forEach((F f) -> action.accept(function.apply(f))); 301 } 302 303 @Override 304 public boolean removeIf(java.util.function.Predicate<? super T> filter) { 305 checkNotNull(filter); 306 return fromCollection.removeIf(element -> filter.test(function.apply(element))); 307 } 308 309 @Override 310 public int size() { 311 return fromCollection.size(); 312 } 313 } 314 315 /** 316 * Returns {@code true} if the collection {@code self} contains all of the elements in the 317 * collection {@code c}. 318 * 319 * <p>This method iterates over the specified collection {@code c}, checking each element returned 320 * by the iterator in turn to see if it is contained in the specified collection {@code self}. If 321 * all elements are so contained, {@code true} is returned, otherwise {@code false}. 322 * 323 * @param self a collection which might contain all elements in {@code c} 324 * @param c a collection whose elements might be contained by {@code self} 325 */ 326 static boolean containsAllImpl(Collection<?> self, Collection<?> c) { 327 for (Object o : c) { 328 if (!self.contains(o)) { 329 return false; 330 } 331 } 332 return true; 333 } 334 335 /** An implementation of {@link Collection#toString()}. */ 336 static String toStringImpl(final Collection<?> collection) { 337 StringBuilder sb = newStringBuilderForCollection(collection.size()).append('['); 338 boolean first = true; 339 for (Object o : collection) { 340 if (!first) { 341 sb.append(", "); 342 } 343 first = false; 344 if (o == collection) { 345 sb.append("(this Collection)"); 346 } else { 347 sb.append(o); 348 } 349 } 350 return sb.append(']').toString(); 351 } 352 353 /** Returns best-effort-sized StringBuilder based on the given collection size. */ 354 static StringBuilder newStringBuilderForCollection(int size) { 355 checkNonnegative(size, "size"); 356 return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO)); 357 } 358 359 /** 360 * Returns a {@link Collection} of all the permutations of the specified {@link Iterable}. 361 * 362 * <p><i>Notes:</i> This is an implementation of the algorithm for Lexicographical Permutations 363 * Generation, described in Knuth's "The Art of Computer Programming", Volume 4, Chapter 7, 364 * Section 7.2.1.2. The iteration order follows the lexicographical order. This means that the 365 * first permutation will be in ascending order, and the last will be in descending order. 366 * 367 * <p>Duplicate elements are considered equal. For example, the list [1, 1] will have only one 368 * permutation, instead of two. This is why the elements have to implement {@link Comparable}. 369 * 370 * <p>An empty iterable has only one permutation, which is an empty list. 371 * 372 * <p>This method is equivalent to {@code Collections2.orderedPermutations(list, 373 * Ordering.natural())}. 374 * 375 * @param elements the original iterable whose elements have to be permuted. 376 * @return an immutable {@link Collection} containing all the different permutations of the 377 * original iterable. 378 * @throws NullPointerException if the specified iterable is null or has any null elements. 379 * @since 12.0 380 */ 381 public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations( 382 Iterable<E> elements) { 383 return orderedPermutations(elements, Ordering.natural()); 384 } 385 386 /** 387 * Returns a {@link Collection} of all the permutations of the specified {@link Iterable} using 388 * the specified {@link Comparator} for establishing the lexicographical ordering. 389 * 390 * <p>Examples: 391 * 392 * <pre>{@code 393 * for (List<String> perm : orderedPermutations(asList("b", "c", "a"))) { 394 * println(perm); 395 * } 396 * // -> ["a", "b", "c"] 397 * // -> ["a", "c", "b"] 398 * // -> ["b", "a", "c"] 399 * // -> ["b", "c", "a"] 400 * // -> ["c", "a", "b"] 401 * // -> ["c", "b", "a"] 402 * 403 * for (List<Integer> perm : orderedPermutations(asList(1, 2, 2, 1))) { 404 * println(perm); 405 * } 406 * // -> [1, 1, 2, 2] 407 * // -> [1, 2, 1, 2] 408 * // -> [1, 2, 2, 1] 409 * // -> [2, 1, 1, 2] 410 * // -> [2, 1, 2, 1] 411 * // -> [2, 2, 1, 1] 412 * }</pre> 413 * 414 * <p><i>Notes:</i> This is an implementation of the algorithm for Lexicographical Permutations 415 * Generation, described in Knuth's "The Art of Computer Programming", Volume 4, Chapter 7, 416 * Section 7.2.1.2. The iteration order follows the lexicographical order. This means that the 417 * first permutation will be in ascending order, and the last will be in descending order. 418 * 419 * <p>Elements that compare equal are considered equal and no new permutations are created by 420 * swapping them. 421 * 422 * <p>An empty iterable has only one permutation, which is an empty list. 423 * 424 * @param elements the original iterable whose elements have to be permuted. 425 * @param comparator a comparator for the iterable's elements. 426 * @return an immutable {@link Collection} containing all the different permutations of the 427 * original iterable. 428 * @throws NullPointerException If the specified iterable is null, has any null elements, or if 429 * the specified comparator is null. 430 * @since 12.0 431 */ 432 public static <E> Collection<List<E>> orderedPermutations( 433 Iterable<E> elements, Comparator<? super E> comparator) { 434 return new OrderedPermutationCollection<E>(elements, comparator); 435 } 436 437 private static final class OrderedPermutationCollection<E> extends AbstractCollection<List<E>> { 438 final ImmutableList<E> inputList; 439 final Comparator<? super E> comparator; 440 final int size; 441 442 OrderedPermutationCollection(Iterable<E> input, Comparator<? super E> comparator) { 443 this.inputList = ImmutableList.sortedCopyOf(comparator, input); 444 this.comparator = comparator; 445 this.size = calculateSize(inputList, comparator); 446 } 447 448 /** 449 * The number of permutations with repeated elements is calculated as follows: 450 * 451 * <ul> 452 * <li>For an empty list, it is 1 (base case). 453 * <li>When r numbers are added to a list of n-r elements, the number of permutations is 454 * increased by a factor of (n choose r). 455 * </ul> 456 */ 457 private static <E> int calculateSize( 458 List<E> sortedInputList, Comparator<? super E> comparator) { 459 int permutations = 1; 460 int n = 1; 461 int r = 1; 462 while (n < sortedInputList.size()) { 463 int comparison = comparator.compare(sortedInputList.get(n - 1), sortedInputList.get(n)); 464 if (comparison < 0) { 465 // We move to the next non-repeated element. 466 permutations = IntMath.saturatedMultiply(permutations, IntMath.binomial(n, r)); 467 r = 0; 468 if (permutations == Integer.MAX_VALUE) { 469 return Integer.MAX_VALUE; 470 } 471 } 472 n++; 473 r++; 474 } 475 return IntMath.saturatedMultiply(permutations, IntMath.binomial(n, r)); 476 } 477 478 @Override 479 public int size() { 480 return size; 481 } 482 483 @Override 484 public boolean isEmpty() { 485 return false; 486 } 487 488 @Override 489 public Iterator<List<E>> iterator() { 490 return new OrderedPermutationIterator<E>(inputList, comparator); 491 } 492 493 @Override 494 public boolean contains(@CheckForNull Object obj) { 495 if (obj instanceof List) { 496 List<?> list = (List<?>) obj; 497 return isPermutation(inputList, list); 498 } 499 return false; 500 } 501 502 @Override 503 public String toString() { 504 return "orderedPermutationCollection(" + inputList + ")"; 505 } 506 } 507 508 private static final class OrderedPermutationIterator<E> extends AbstractIterator<List<E>> { 509 @CheckForNull List<E> nextPermutation; 510 final Comparator<? super E> comparator; 511 512 OrderedPermutationIterator(List<E> list, Comparator<? super E> comparator) { 513 this.nextPermutation = Lists.newArrayList(list); 514 this.comparator = comparator; 515 } 516 517 @Override 518 @CheckForNull 519 protected List<E> computeNext() { 520 if (nextPermutation == null) { 521 return endOfData(); 522 } 523 ImmutableList<E> next = ImmutableList.copyOf(nextPermutation); 524 calculateNextPermutation(); 525 return next; 526 } 527 528 void calculateNextPermutation() { 529 int j = findNextJ(); 530 if (j == -1) { 531 nextPermutation = null; 532 return; 533 } 534 /* 535 * requireNonNull is safe because we don't clear nextPermutation until we're done calling this 536 * method. 537 */ 538 requireNonNull(nextPermutation); 539 540 int l = findNextL(j); 541 Collections.swap(nextPermutation, j, l); 542 int n = nextPermutation.size(); 543 Collections.reverse(nextPermutation.subList(j + 1, n)); 544 } 545 546 int findNextJ() { 547 /* 548 * requireNonNull is safe because we don't clear nextPermutation until we're done calling this 549 * method. 550 */ 551 requireNonNull(nextPermutation); 552 for (int k = nextPermutation.size() - 2; k >= 0; k--) { 553 if (comparator.compare(nextPermutation.get(k), nextPermutation.get(k + 1)) < 0) { 554 return k; 555 } 556 } 557 return -1; 558 } 559 560 int findNextL(int j) { 561 /* 562 * requireNonNull is safe because we don't clear nextPermutation until we're done calling this 563 * method. 564 */ 565 requireNonNull(nextPermutation); 566 E ak = nextPermutation.get(j); 567 for (int l = nextPermutation.size() - 1; l > j; l--) { 568 if (comparator.compare(ak, nextPermutation.get(l)) < 0) { 569 return l; 570 } 571 } 572 throw new AssertionError("this statement should be unreachable"); 573 } 574 } 575 576 /** 577 * Returns a {@link Collection} of all the permutations of the specified {@link Collection}. 578 * 579 * <p><i>Notes:</i> This is an implementation of the Plain Changes algorithm for permutations 580 * generation, described in Knuth's "The Art of Computer Programming", Volume 4, Chapter 7, 581 * Section 7.2.1.2. 582 * 583 * <p>If the input list contains equal elements, some of the generated permutations will be equal. 584 * 585 * <p>An empty collection has only one permutation, which is an empty list. 586 * 587 * @param elements the original collection whose elements have to be permuted. 588 * @return an immutable {@link Collection} containing all the different permutations of the 589 * original collection. 590 * @throws NullPointerException if the specified collection is null or has any null elements. 591 * @since 12.0 592 */ 593 public static <E> Collection<List<E>> permutations(Collection<E> elements) { 594 return new PermutationCollection<E>(ImmutableList.copyOf(elements)); 595 } 596 597 private static final class PermutationCollection<E> extends AbstractCollection<List<E>> { 598 final ImmutableList<E> inputList; 599 600 PermutationCollection(ImmutableList<E> input) { 601 this.inputList = input; 602 } 603 604 @Override 605 public int size() { 606 return IntMath.factorial(inputList.size()); 607 } 608 609 @Override 610 public boolean isEmpty() { 611 return false; 612 } 613 614 @Override 615 public Iterator<List<E>> iterator() { 616 return new PermutationIterator<E>(inputList); 617 } 618 619 @Override 620 public boolean contains(@CheckForNull Object obj) { 621 if (obj instanceof List) { 622 List<?> list = (List<?>) obj; 623 return isPermutation(inputList, list); 624 } 625 return false; 626 } 627 628 @Override 629 public String toString() { 630 return "permutations(" + inputList + ")"; 631 } 632 } 633 634 private static class PermutationIterator<E> extends AbstractIterator<List<E>> { 635 final List<E> list; 636 final int[] c; 637 final int[] o; 638 int j; 639 640 PermutationIterator(List<E> list) { 641 this.list = new ArrayList<>(list); 642 int n = list.size(); 643 c = new int[n]; 644 o = new int[n]; 645 Arrays.fill(c, 0); 646 Arrays.fill(o, 1); 647 j = Integer.MAX_VALUE; 648 } 649 650 @Override 651 @CheckForNull 652 protected List<E> computeNext() { 653 if (j <= 0) { 654 return endOfData(); 655 } 656 ImmutableList<E> next = ImmutableList.copyOf(list); 657 calculateNextPermutation(); 658 return next; 659 } 660 661 void calculateNextPermutation() { 662 j = list.size() - 1; 663 int s = 0; 664 665 // Handle the special case of an empty list. Skip the calculation of the 666 // next permutation. 667 if (j == -1) { 668 return; 669 } 670 671 while (true) { 672 int q = c[j] + o[j]; 673 if (q < 0) { 674 switchDirection(); 675 continue; 676 } 677 if (q == j + 1) { 678 if (j == 0) { 679 break; 680 } 681 s++; 682 switchDirection(); 683 continue; 684 } 685 686 Collections.swap(list, j - c[j] + s, j - q + s); 687 c[j] = q; 688 break; 689 } 690 } 691 692 void switchDirection() { 693 o[j] = -o[j]; 694 j--; 695 } 696 } 697 698 /** Returns {@code true} if the second list is a permutation of the first. */ 699 private static boolean isPermutation(List<?> first, List<?> second) { 700 if (first.size() != second.size()) { 701 return false; 702 } 703 Multiset<?> firstMultiset = HashMultiset.create(first); 704 Multiset<?> secondMultiset = HashMultiset.create(second); 705 return firstMultiset.equals(secondMultiset); 706 } 707}