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