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