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