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