001/*
002 * Copyright (C) 2007 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;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.base.Predicate;
026import com.google.common.base.Predicates;
027import com.google.common.collect.Collections2.FilteredCollection;
028import com.google.common.math.IntMath;
029import com.google.errorprone.annotations.CanIgnoreReturnValue;
030import java.io.Serializable;
031import java.util.AbstractSet;
032import java.util.Arrays;
033import java.util.Collection;
034import java.util.Collections;
035import java.util.Comparator;
036import java.util.EnumSet;
037import java.util.HashSet;
038import java.util.Iterator;
039import java.util.LinkedHashSet;
040import java.util.List;
041import java.util.Map;
042import java.util.NavigableSet;
043import java.util.NoSuchElementException;
044import java.util.Set;
045import java.util.SortedSet;
046import java.util.TreeSet;
047import java.util.concurrent.ConcurrentHashMap;
048import java.util.concurrent.CopyOnWriteArraySet;
049import javax.annotation.Nullable;
050
051/**
052 * Static utility methods pertaining to {@link Set} instances. Also see this
053 * class's counterparts {@link Lists}, {@link Maps} and {@link Queues}.
054 *
055 * <p>See the Guava User Guide article on <a href=
056 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#sets">
057 * {@code Sets}</a>.
058 *
059 * @author Kevin Bourrillion
060 * @author Jared Levy
061 * @author Chris Povirk
062 * @since 2.0
063 */
064@GwtCompatible(emulated = true)
065public final class Sets {
066  private Sets() {}
067
068  /**
069   * {@link AbstractSet} substitute without the potentially-quadratic
070   * {@code removeAll} implementation.
071   */
072  abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
073    @Override
074    public boolean removeAll(Collection<?> c) {
075      return removeAllImpl(this, c);
076    }
077
078    @Override
079    public boolean retainAll(Collection<?> c) {
080      return super.retainAll(checkNotNull(c)); // GWT compatibility
081    }
082  }
083
084  /**
085   * Returns an immutable set instance containing the given enum elements.
086   * Internally, the returned set will be backed by an {@link EnumSet}.
087   *
088   * <p>The iteration order of the returned set follows the enum's iteration
089   * order, not the order in which the elements are provided to the method.
090   *
091   * @param anElement one of the elements the set should contain
092   * @param otherElements the rest of the elements the set should contain
093   * @return an immutable set containing those elements, minus duplicates
094   */
095  // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
096  @GwtCompatible(serializable = true)
097  public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
098      E anElement, E... otherElements) {
099    return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements));
100  }
101
102  /**
103   * Returns an immutable set instance containing the given enum elements.
104   * Internally, the returned set will be backed by an {@link EnumSet}.
105   *
106   * <p>The iteration order of the returned set follows the enum's iteration
107   * order, not the order in which the elements appear in the given collection.
108   *
109   * @param elements the elements, all of the same {@code enum} type, that the
110   *     set should contain
111   * @return an immutable set containing those elements, minus duplicates
112   */
113  // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
114  @GwtCompatible(serializable = true)
115  public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(Iterable<E> elements) {
116    if (elements instanceof ImmutableEnumSet) {
117      return (ImmutableEnumSet<E>) elements;
118    } else if (elements instanceof Collection) {
119      Collection<E> collection = (Collection<E>) elements;
120      if (collection.isEmpty()) {
121        return ImmutableSet.of();
122      } else {
123        return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection));
124      }
125    } else {
126      Iterator<E> itr = elements.iterator();
127      if (itr.hasNext()) {
128        EnumSet<E> enumSet = EnumSet.of(itr.next());
129        Iterators.addAll(enumSet, itr);
130        return ImmutableEnumSet.asImmutable(enumSet);
131      } else {
132        return ImmutableSet.of();
133      }
134    }
135  }
136
137  /**
138   * Returns a new, <i>mutable</i> {@code EnumSet} instance containing the given elements in their
139   * natural order. This method behaves identically to {@link EnumSet#copyOf(Collection)}, but also
140   * accepts non-{@code Collection} iterables and empty iterables.
141   */
142  public static <E extends Enum<E>> EnumSet<E> newEnumSet(
143      Iterable<E> iterable, Class<E> elementType) {
144    EnumSet<E> set = EnumSet.noneOf(elementType);
145    Iterables.addAll(set, iterable);
146    return set;
147  }
148
149  // HashSet
150
151  /**
152   * Creates a <i>mutable</i>, initially empty {@code HashSet} instance.
153   *
154   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSet#of()} instead. If
155   * {@code E} is an {@link Enum} type, use {@link EnumSet#noneOf} instead. Otherwise, strongly
156   * consider using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to
157   * get deterministic iteration behavior.
158   *
159   * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
160   * deprecated. Instead, use the {@code HashSet} constructor directly, taking advantage of the new
161   * <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
162   */
163  public static <E> HashSet<E> newHashSet() {
164    return new HashSet<E>();
165  }
166
167  /**
168   * Creates a <i>mutable</i> {@code HashSet} instance initially containing the given elements.
169   *
170   * <p><b>Note:</b> if elements are non-null and won't be added or removed after this point, use
171   * {@link ImmutableSet#of()} or {@link ImmutableSet#copyOf(Object[])} instead. If {@code E} is an
172   * {@link Enum} type, use {@link EnumSet#of(Enum, Enum[])} instead. Otherwise, strongly consider
173   * using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to get
174   * deterministic iteration behavior.
175   *
176   * <p>This method is just a small convenience, either for {@code newHashSet(}{@link Arrays#asList
177   * asList}{@code (...))}, or for creating an empty set then calling {@link Collections#addAll}.
178   * This method is not actually very useful and will likely be deprecated in the future.
179   */
180  public static <E> HashSet<E> newHashSet(E... elements) {
181    HashSet<E> set = newHashSetWithExpectedSize(elements.length);
182    Collections.addAll(set, elements);
183    return set;
184  }
185
186  /**
187   * Returns a new hash set using the smallest initial table size that can hold {@code expectedSize}
188   * elements without resizing. Note that this is not what {@link HashSet#HashSet(int)} does, but it
189   * is what most users want and expect it to do.
190   *
191   * <p>This behavior can't be broadly guaranteed, but has been tested with OpenJDK 1.7 and 1.8.
192   *
193   * @param expectedSize the number of elements you expect to add to the returned set
194   * @return a new, empty hash set with enough capacity to hold {@code expectedSize} elements
195   *     without resizing
196   * @throws IllegalArgumentException if {@code expectedSize} is negative
197   */
198  public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
199    return new HashSet<E>(Maps.capacity(expectedSize));
200  }
201
202  /**
203   * Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin
204   * convenience for creating an empty set then calling {@link Collection#addAll} or {@link
205   * Iterables#addAll}.
206   *
207   * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
208   * ImmutableSet#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link
209   * FluentIterable} and call {@code elements.toSet()}.)
210   *
211   * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link #newEnumSet(Iterable, Class)}
212   * instead.
213   *
214   * <p><b>Note for Java 7 and later:</b> if {@code elements} is a {@link Collection}, you don't
215   * need this method. Instead, use the {@code HashSet} constructor directly, taking advantage of
216   * the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
217   *
218   * <p>Overall, this method is not very useful and will likely be deprecated in the future.
219   */
220  public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
221    return (elements instanceof Collection)
222        ? new HashSet<E>(Collections2.cast(elements))
223        : newHashSet(elements.iterator());
224  }
225
226  /**
227   * Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin
228   * convenience for creating an empty set and then calling {@link Iterators#addAll}.
229   *
230   * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
231   * ImmutableSet#copyOf(Iterator)} instead.
232   *
233   * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an {@link EnumSet}
234   * instead.
235   *
236   * <p>Overall, this method is not very useful and will likely be deprecated in the future.
237   */
238  public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
239    HashSet<E> set = newHashSet();
240    Iterators.addAll(set, elements);
241    return set;
242  }
243
244  /**
245   * Creates a thread-safe set backed by a hash map. The set is backed by a
246   * {@link ConcurrentHashMap} instance, and thus carries the same concurrency
247   * guarantees.
248   *
249   * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
250   * used as an element. The set is serializable.
251   *
252   * @return a new, empty thread-safe {@code Set}
253   * @since 15.0
254   */
255  public static <E> Set<E> newConcurrentHashSet() {
256    return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>());
257  }
258
259  /**
260   * Creates a thread-safe set backed by a hash map and containing the given
261   * elements. The set is backed by a {@link ConcurrentHashMap} instance, and
262   * thus carries the same concurrency guarantees.
263   *
264   * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
265   * used as an element. The set is serializable.
266   *
267   * @param elements the elements that the set should contain
268   * @return a new thread-safe set containing those elements (minus duplicates)
269   * @throws NullPointerException if {@code elements} or any of its contents is
270   *      null
271   * @since 15.0
272   */
273  public static <E> Set<E> newConcurrentHashSet(Iterable<? extends E> elements) {
274    Set<E> set = newConcurrentHashSet();
275    Iterables.addAll(set, elements);
276    return set;
277  }
278
279  // LinkedHashSet
280
281  /**
282   * Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
283   *
284   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSet#of()} instead.
285   *
286   * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
287   * deprecated. Instead, use the {@code LinkedHashSet} constructor directly, taking advantage of
288   * the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
289   *
290   * @return a new, empty {@code LinkedHashSet}
291   */
292  public static <E> LinkedHashSet<E> newLinkedHashSet() {
293    return new LinkedHashSet<E>();
294  }
295
296  /**
297   * Creates a {@code LinkedHashSet} instance, with a high enough "initial capacity" that it
298   * <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be
299   * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
300   * that the method isn't inadvertently <i>oversizing</i> the returned set.
301   *
302   * @param expectedSize the number of elements you expect to add to the returned set
303   * @return a new, empty {@code LinkedHashSet} with enough capacity to hold {@code expectedSize}
304   *         elements without resizing
305   * @throws IllegalArgumentException if {@code expectedSize} is negative
306   * @since 11.0
307   */
308  public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(int expectedSize) {
309    return new LinkedHashSet<E>(Maps.capacity(expectedSize));
310  }
311
312  /**
313   * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the given elements in order.
314   *
315   * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
316   * ImmutableSet#copyOf(Iterable)} instead.
317   *
318   * <p><b>Note for Java 7 and later:</b> if {@code elements} is a {@link Collection}, you don't
319   * need this method. Instead, use the {@code LinkedHashSet} constructor directly, taking advantage
320   * of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
321   *
322   * <p>Overall, this method is not very useful and will likely be deprecated in the future.
323   *
324   * @param elements the elements that the set should contain, in order
325   * @return a new {@code LinkedHashSet} containing those elements (minus duplicates)
326   */
327  public static <E> LinkedHashSet<E> newLinkedHashSet(Iterable<? extends E> elements) {
328    if (elements instanceof Collection) {
329      return new LinkedHashSet<E>(Collections2.cast(elements));
330    }
331    LinkedHashSet<E> set = newLinkedHashSet();
332    Iterables.addAll(set, elements);
333    return set;
334  }
335
336  // TreeSet
337
338  /**
339   * Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the natural sort ordering of
340   * its elements.
341   *
342   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#of()} instead.
343   *
344   * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
345   * deprecated. Instead, use the {@code TreeSet} constructor directly, taking advantage of the new
346   * <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
347   *
348   * @return a new, empty {@code TreeSet}
349   */
350  public static <E extends Comparable> TreeSet<E> newTreeSet() {
351    return new TreeSet<E>();
352  }
353
354  /**
355   * Creates a <i>mutable</i> {@code TreeSet} instance containing the given elements sorted by their
356   * natural ordering.
357   *
358   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#copyOf(Iterable)}
359   * instead.
360   *
361   * <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit comparator, this
362   * method has different behavior than {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code
363   * TreeSet} with that comparator.
364   *
365   * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
366   * deprecated. Instead, use the {@code TreeSet} constructor directly, taking advantage of the new
367   * <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
368   *
369   * <p>This method is just a small convenience for creating an empty set and then calling {@link
370   * Iterables#addAll}. This method is not very useful and will likely be deprecated in the future.
371   *
372   * @param elements the elements that the set should contain
373   * @return a new {@code TreeSet} containing those elements (minus duplicates)
374   */
375  public static <E extends Comparable> TreeSet<E> newTreeSet(Iterable<? extends E> elements) {
376    TreeSet<E> set = newTreeSet();
377    Iterables.addAll(set, elements);
378    return set;
379  }
380
381  /**
382   * Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given comparator.
383   *
384   * <p><b>Note:</b> if mutability is not required, use {@code
385   * ImmutableSortedSet.orderedBy(comparator).build()} instead.
386   *
387   * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
388   * deprecated. Instead, use the {@code TreeSet} constructor directly, taking advantage of the new
389   * <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. One caveat to this is that the {@code
390   * TreeSet} constructor uses a null {@code Comparator} to mean "natural ordering," whereas this
391   * factory rejects null. Clean your code accordingly.
392   *
393   * @param comparator the comparator to use to sort the set
394   * @return a new, empty {@code TreeSet}
395   * @throws NullPointerException if {@code comparator} is null
396   */
397  public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
398    return new TreeSet<E>(checkNotNull(comparator));
399  }
400
401  /**
402   * Creates an empty {@code Set} that uses identity to determine equality. It
403   * compares object references, instead of calling {@code equals}, to
404   * determine whether a provided object matches an element in the set. For
405   * example, {@code contains} returns {@code false} when passed an object that
406   * equals a set member, but isn't the same instance. This behavior is similar
407   * to the way {@code IdentityHashMap} handles key lookups.
408   *
409   * @since 8.0
410   */
411  public static <E> Set<E> newIdentityHashSet() {
412    return Collections.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
413  }
414
415  /**
416   * Creates an empty {@code CopyOnWriteArraySet} instance.
417   *
418   * <p><b>Note:</b> if you need an immutable empty {@link Set}, use
419   * {@link Collections#emptySet} instead.
420   *
421   * @return a new, empty {@code CopyOnWriteArraySet}
422   * @since 12.0
423   */
424  @GwtIncompatible // CopyOnWriteArraySet
425  public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
426    return new CopyOnWriteArraySet<E>();
427  }
428
429  /**
430   * Creates a {@code CopyOnWriteArraySet} instance containing the given elements.
431   *
432   * @param elements the elements that the set should contain, in order
433   * @return a new {@code CopyOnWriteArraySet} containing those elements
434   * @since 12.0
435   */
436  @GwtIncompatible // CopyOnWriteArraySet
437  public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(Iterable<? extends E> elements) {
438    // We copy elements to an ArrayList first, rather than incurring the
439    // quadratic cost of adding them to the COWAS directly.
440    Collection<? extends E> elementsCollection =
441        (elements instanceof Collection)
442            ? Collections2.cast(elements)
443            : Lists.newArrayList(elements);
444    return new CopyOnWriteArraySet<E>(elementsCollection);
445  }
446
447  /**
448   * Creates an {@code EnumSet} consisting of all enum values that are not in
449   * the specified collection. If the collection is an {@link EnumSet}, this
450   * method has the same behavior as {@link EnumSet#complementOf}. Otherwise,
451   * the specified collection must contain at least one element, in order to
452   * determine the element type. If the collection could be empty, use
453   * {@link #complementOf(Collection, Class)} instead of this method.
454   *
455   * @param collection the collection whose complement should be stored in the
456   *     enum set
457   * @return a new, modifiable {@code EnumSet} containing all values of the enum
458   *     that aren't present in the given collection
459   * @throws IllegalArgumentException if {@code collection} is not an
460   *     {@code EnumSet} instance and contains no elements
461   */
462  public static <E extends Enum<E>> EnumSet<E> complementOf(Collection<E> collection) {
463    if (collection instanceof EnumSet) {
464      return EnumSet.complementOf((EnumSet<E>) collection);
465    }
466    checkArgument(
467        !collection.isEmpty(), "collection is empty; use the other version of this method");
468    Class<E> type = collection.iterator().next().getDeclaringClass();
469    return makeComplementByHand(collection, type);
470  }
471
472  /**
473   * Creates an {@code EnumSet} consisting of all enum values that are not in
474   * the specified collection. This is equivalent to
475   * {@link EnumSet#complementOf}, but can act on any input collection, as long
476   * as the elements are of enum type.
477   *
478   * @param collection the collection whose complement should be stored in the
479   *     {@code EnumSet}
480   * @param type the type of the elements in the set
481   * @return a new, modifiable {@code EnumSet} initially containing all the
482   *     values of the enum not present in the given collection
483   */
484  public static <E extends Enum<E>> EnumSet<E> complementOf(
485      Collection<E> collection, Class<E> type) {
486    checkNotNull(collection);
487    return (collection instanceof EnumSet)
488        ? EnumSet.complementOf((EnumSet<E>) collection)
489        : makeComplementByHand(collection, type);
490  }
491
492  private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
493      Collection<E> collection, Class<E> type) {
494    EnumSet<E> result = EnumSet.allOf(type);
495    result.removeAll(collection);
496    return result;
497  }
498
499  /**
500   * Returns a set backed by the specified map. The resulting set displays
501   * the same ordering, concurrency, and performance characteristics as the
502   * backing map. In essence, this factory method provides a {@link Set}
503   * implementation corresponding to any {@link Map} implementation. There is no
504   * need to use this method on a {@link Map} implementation that already has a
505   * corresponding {@link Set} implementation (such as {@link java.util.HashMap}
506   * or {@link java.util.TreeMap}).
507   *
508   * <p>Each method invocation on the set returned by this method results in
509   * exactly one method invocation on the backing map or its {@code keySet}
510   * view, with one exception. The {@code addAll} method is implemented as a
511   * sequence of {@code put} invocations on the backing map.
512   *
513   * <p>The specified map must be empty at the time this method is invoked,
514   * and should not be accessed directly after this method returns. These
515   * conditions are ensured if the map is created empty, passed directly
516   * to this method, and no reference to the map is retained, as illustrated
517   * in the following code fragment: <pre>  {@code
518   *
519   *   Set<Object> identityHashSet = Sets.newSetFromMap(
520   *       new IdentityHashMap<Object, Boolean>());}</pre>
521   *
522   * <p>The returned set is serializable if the backing map is.
523   *
524   * @param map the backing map
525   * @return the set backed by the map
526   * @throws IllegalArgumentException if {@code map} is not empty
527   * @deprecated Use {@link Collections#newSetFromMap} instead. This method
528   *     will be removed in December 2017.
529   */
530  @Deprecated
531  public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
532    return Collections.newSetFromMap(map);
533  }
534
535  /**
536   * An unmodifiable view of a set which may be backed by other sets; this view
537   * will change as the backing sets do. Contains methods to copy the data into
538   * a new set which will then remain stable. There is usually no reason to
539   * retain a reference of type {@code SetView}; typically, you either use it
540   * as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
541   * {@link #copyInto} and forget the {@code SetView} itself.
542   *
543   * @since 2.0
544   */
545  public abstract static class SetView<E> extends AbstractSet<E> {
546    private SetView() {} // no subclasses but our own
547
548    /**
549     * Returns an immutable copy of the current contents of this set view.
550     * Does not support null elements.
551     *
552     * <p><b>Warning:</b> this may have unexpected results if a backing set of
553     * this view uses a nonstandard notion of equivalence, for example if it is
554     * a {@link TreeSet} using a comparator that is inconsistent with {@link
555     * Object#equals(Object)}.
556     */
557    public ImmutableSet<E> immutableCopy() {
558      return ImmutableSet.copyOf(this);
559    }
560
561    /**
562     * Copies the current contents of this set view into an existing set. This
563     * method has equivalent behavior to {@code set.addAll(this)}, assuming that
564     * all the sets involved are based on the same notion of equivalence.
565     *
566     * @return a reference to {@code set}, for convenience
567     */
568    // Note: S should logically extend Set<? super E> but can't due to either
569    // some javac bug or some weirdness in the spec, not sure which.
570    @CanIgnoreReturnValue
571    public <S extends Set<E>> S copyInto(S set) {
572      set.addAll(this);
573      return set;
574    }
575
576    /**
577     * Guaranteed to throw an exception and leave the collection unmodified.
578     *
579     * @throws UnsupportedOperationException always
580     * @deprecated Unsupported operation.
581     */
582    @CanIgnoreReturnValue
583    @Deprecated
584    @Override
585    public final boolean add(E e) {
586      throw new UnsupportedOperationException();
587    }
588
589    /**
590     * Guaranteed to throw an exception and leave the collection unmodified.
591     *
592     * @throws UnsupportedOperationException always
593     * @deprecated Unsupported operation.
594     */
595    @CanIgnoreReturnValue
596    @Deprecated
597    @Override
598    public final boolean remove(Object object) {
599      throw new UnsupportedOperationException();
600    }
601
602    /**
603     * Guaranteed to throw an exception and leave the collection unmodified.
604     *
605     * @throws UnsupportedOperationException always
606     * @deprecated Unsupported operation.
607     */
608    @CanIgnoreReturnValue
609    @Deprecated
610    @Override
611    public final boolean addAll(Collection<? extends E> newElements) {
612      throw new UnsupportedOperationException();
613    }
614
615    /**
616     * Guaranteed to throw an exception and leave the collection unmodified.
617     *
618     * @throws UnsupportedOperationException always
619     * @deprecated Unsupported operation.
620     */
621    @CanIgnoreReturnValue
622    @Deprecated
623    @Override
624    public final boolean removeAll(Collection<?> oldElements) {
625      throw new UnsupportedOperationException();
626    }
627
628    /**
629     * Guaranteed to throw an exception and leave the collection unmodified.
630     *
631     * @throws UnsupportedOperationException always
632     * @deprecated Unsupported operation.
633     */
634    @CanIgnoreReturnValue
635    @Deprecated
636    @Override
637    public final boolean retainAll(Collection<?> elementsToKeep) {
638      throw new UnsupportedOperationException();
639    }
640
641    /**
642     * Guaranteed to throw an exception and leave the collection unmodified.
643     *
644     * @throws UnsupportedOperationException always
645     * @deprecated Unsupported operation.
646     */
647    @Deprecated
648    @Override
649    public final void clear() {
650      throw new UnsupportedOperationException();
651    }
652
653    /**
654     * Scope the return type to {@link UnmodifiableIterator} to ensure this is an unmodifiable view.
655     *
656     * @since 20.0 (present with return type {@link Iterator} since 2.0)
657     */
658    @Override
659    public abstract UnmodifiableIterator<E> iterator();
660  }
661
662  /**
663   * Returns an unmodifiable <b>view</b> of the union of two sets. The returned
664   * set contains all elements that are contained in either backing set.
665   * Iterating over the returned set iterates first over all the elements of
666   * {@code set1}, then over each element of {@code set2}, in order, that is not
667   * contained in {@code set1}.
668   *
669   * <p>Results are undefined if {@code set1} and {@code set2} are sets based on
670   * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and
671   * the {@link Map#keySet} of an {@code IdentityHashMap} all are).
672   */
673  public static <E> SetView<E> union(final Set<? extends E> set1, final Set<? extends E> set2) {
674    checkNotNull(set1, "set1");
675    checkNotNull(set2, "set2");
676
677    final Set<? extends E> set2minus1 = difference(set2, set1);
678
679    return new SetView<E>() {
680      @Override
681      public int size() {
682        return IntMath.saturatedAdd(set1.size(), set2minus1.size());
683      }
684
685      @Override
686      public boolean isEmpty() {
687        return set1.isEmpty() && set2.isEmpty();
688      }
689
690      @Override
691      public UnmodifiableIterator<E> iterator() {
692        return Iterators.unmodifiableIterator(
693            Iterators.concat(set1.iterator(), set2minus1.iterator()));
694      }
695
696      @Override
697      public boolean contains(Object object) {
698        return set1.contains(object) || set2.contains(object);
699      }
700
701      @Override
702      public <S extends Set<E>> S copyInto(S set) {
703        set.addAll(set1);
704        set.addAll(set2);
705        return set;
706      }
707
708      @Override
709      public ImmutableSet<E> immutableCopy() {
710        return new ImmutableSet.Builder<E>().addAll(set1).addAll(set2).build();
711      }
712    };
713  }
714
715  /**
716   * Returns an unmodifiable <b>view</b> of the intersection of two sets. The
717   * returned set contains all elements that are contained by both backing sets.
718   * The iteration order of the returned set matches that of {@code set1}.
719   *
720   * <p>Results are undefined if {@code set1} and {@code set2} are sets based
721   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
722   * and the keySet of an {@code IdentityHashMap} all are).
723   *
724   * <p><b>Note:</b> The returned view performs slightly better when {@code
725   * set1} is the smaller of the two sets. If you have reason to believe one of
726   * your sets will generally be smaller than the other, pass it first.
727   * Unfortunately, since this method sets the generic type of the returned set
728   * based on the type of the first set passed, this could in rare cases force
729   * you to make a cast, for example: <pre>   {@code
730   *
731   *   Set<Object> aFewBadObjects = ...
732   *   Set<String> manyBadStrings = ...
733   *
734   *   // impossible for a non-String to be in the intersection
735   *   SuppressWarnings("unchecked")
736   *   Set<String> badStrings = (Set) Sets.intersection(
737   *       aFewBadObjects, manyBadStrings);}</pre>
738   *
739   * <p>This is unfortunate, but should come up only very rarely.
740   */
741  public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2) {
742    checkNotNull(set1, "set1");
743    checkNotNull(set2, "set2");
744
745    final Predicate<Object> inSet2 = Predicates.in(set2);
746    return new SetView<E>() {
747      @Override
748      public UnmodifiableIterator<E> iterator() {
749        return Iterators.filter(set1.iterator(), inSet2);
750      }
751
752      @Override
753      public int size() {
754        return Iterators.size(iterator());
755      }
756
757      @Override
758      public boolean isEmpty() {
759        return !iterator().hasNext();
760      }
761
762      @Override
763      public boolean contains(Object object) {
764        return set1.contains(object) && set2.contains(object);
765      }
766
767      @Override
768      public boolean containsAll(Collection<?> collection) {
769        return set1.containsAll(collection) && set2.containsAll(collection);
770      }
771    };
772  }
773
774  /**
775   * Returns an unmodifiable <b>view</b> of the difference of two sets. The
776   * returned set contains all elements that are contained by {@code set1} and
777   * not contained by {@code set2}. {@code set2} may also contain elements not
778   * present in {@code set1}; these are simply ignored. The iteration order of
779   * the returned set matches that of {@code set1}.
780   *
781   * <p>Results are undefined if {@code set1} and {@code set2} are sets based
782   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
783   * and the keySet of an {@code IdentityHashMap} all are).
784   */
785  public static <E> SetView<E> difference(final Set<E> set1, final Set<?> set2) {
786    checkNotNull(set1, "set1");
787    checkNotNull(set2, "set2");
788
789    final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
790    return new SetView<E>() {
791      @Override
792      public UnmodifiableIterator<E> iterator() {
793        return Iterators.filter(set1.iterator(), notInSet2);
794      }
795
796      @Override
797      public int size() {
798        return Iterators.size(iterator());
799      }
800
801      @Override
802      public boolean isEmpty() {
803        return set2.containsAll(set1);
804      }
805
806      @Override
807      public boolean contains(Object element) {
808        return set1.contains(element) && !set2.contains(element);
809      }
810    };
811  }
812
813  /**
814   * Returns an unmodifiable <b>view</b> of the symmetric difference of two
815   * sets. The returned set contains all elements that are contained in either
816   * {@code set1} or {@code set2} but not in both. The iteration order of the
817   * returned set is undefined.
818   *
819   * <p>Results are undefined if {@code set1} and {@code set2} are sets based
820   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
821   * and the keySet of an {@code IdentityHashMap} all are).
822   *
823   * @since 3.0
824   */
825  public static <E> SetView<E> symmetricDifference(
826      final Set<? extends E> set1, final Set<? extends E> set2) {
827    checkNotNull(set1, "set1");
828    checkNotNull(set2, "set2");
829
830    return new SetView<E>() {
831      @Override
832      public UnmodifiableIterator<E> iterator() {
833        final Iterator<? extends E> itr1 = set1.iterator();
834        final Iterator<? extends E> itr2 = set2.iterator();
835        return new AbstractIterator<E>() {
836          @Override
837          public E computeNext() {
838            while (itr1.hasNext()) {
839              E elem1 = itr1.next();
840              if (!set2.contains(elem1)) {
841                return elem1;
842              }
843            }
844            while (itr2.hasNext()) {
845              E elem2 = itr2.next();
846              if (!set1.contains(elem2)) {
847                return elem2;
848              }
849            }
850            return endOfData();
851          }
852        };
853      }
854
855      @Override
856      public int size() {
857        return Iterators.size(iterator());
858      }
859
860      @Override
861      public boolean isEmpty() {
862        return set1.equals(set2);
863      }
864
865      @Override
866      public boolean contains(Object element) {
867        return set1.contains(element) ^ set2.contains(element);
868      }
869    };
870  }
871
872  /**
873   * Returns the elements of {@code unfiltered} that satisfy a predicate. The
874   * returned set is a live view of {@code unfiltered}; changes to one affect
875   * the other.
876   *
877   * <p>The resulting set's iterator does not support {@code remove()}, but all
878   * other set methods are supported. When given an element that doesn't satisfy
879   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
880   * an {@link IllegalArgumentException}. When methods such as {@code
881   * removeAll()} and {@code clear()} are called on the filtered set, only
882   * elements that satisfy the filter will be removed from the underlying set.
883   *
884   * <p>The returned set isn't threadsafe or serializable, even if
885   * {@code unfiltered} is.
886   *
887   * <p>Many of the filtered set's methods, such as {@code size()}, iterate
888   * across every element in the underlying set and determine which elements
889   * satisfy the filter. When a live view is <i>not</i> needed, it may be faster
890   * to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy.
891   *
892   * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
893   * as documented at {@link Predicate#apply}. Do not provide a predicate such
894   * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
895   * with equals. (See {@link Iterables#filter(Iterable, Class)} for related
896   * functionality.)
897   *
898   * <p><b>Java 8 users:</b> many use cases for this method are better
899   * addressed by {@link java.util.stream.Stream#filter}. This method is not
900   * being deprecated, but we gently encourage you to migrate to streams.
901   */
902  // TODO(kevinb): how to omit that last sentence when building GWT javadoc?
903  public static <E> Set<E> filter(Set<E> unfiltered, Predicate<? super E> predicate) {
904    if (unfiltered instanceof SortedSet) {
905      return filter((SortedSet<E>) unfiltered, predicate);
906    }
907    if (unfiltered instanceof FilteredSet) {
908      // Support clear(), removeAll(), and retainAll() when filtering a filtered
909      // collection.
910      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
911      Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate);
912      return new FilteredSet<E>((Set<E>) filtered.unfiltered, combinedPredicate);
913    }
914
915    return new FilteredSet<E>(checkNotNull(unfiltered), checkNotNull(predicate));
916  }
917
918  private static class FilteredSet<E> extends FilteredCollection<E> implements Set<E> {
919    FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
920      super(unfiltered, predicate);
921    }
922
923    @Override
924    public boolean equals(@Nullable Object object) {
925      return equalsImpl(this, object);
926    }
927
928    @Override
929    public int hashCode() {
930      return hashCodeImpl(this);
931    }
932  }
933
934  /**
935   * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that
936   * satisfy a predicate. The returned set is a live view of {@code unfiltered};
937   * changes to one affect the other.
938   *
939   * <p>The resulting set's iterator does not support {@code remove()}, but all
940   * other set methods are supported. When given an element that doesn't satisfy
941   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
942   * an {@link IllegalArgumentException}. When methods such as
943   * {@code removeAll()} and {@code clear()} are called on the filtered set,
944   * only elements that satisfy the filter will be removed from the underlying
945   * set.
946   *
947   * <p>The returned set isn't threadsafe or serializable, even if
948   * {@code unfiltered} is.
949   *
950   * <p>Many of the filtered set's methods, such as {@code size()}, iterate across
951   * every element in the underlying set and determine which elements satisfy
952   * the filter. When a live view is <i>not</i> needed, it may be faster to copy
953   * {@code Iterables.filter(unfiltered, predicate)} and use the copy.
954   *
955   * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
956   * as documented at {@link Predicate#apply}. Do not provide a predicate such as
957   * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
958   * equals. (See {@link Iterables#filter(Iterable, Class)} for related
959   * functionality.)
960   *
961   * @since 11.0
962   */
963  public static <E> SortedSet<E> filter(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
964    if (unfiltered instanceof FilteredSet) {
965      // Support clear(), removeAll(), and retainAll() when filtering a filtered
966      // collection.
967      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
968      Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate);
969      return new FilteredSortedSet<E>((SortedSet<E>) filtered.unfiltered, combinedPredicate);
970    }
971
972    return new FilteredSortedSet<E>(checkNotNull(unfiltered), checkNotNull(predicate));
973  }
974
975  private static class FilteredSortedSet<E> extends FilteredSet<E> implements SortedSet<E> {
976
977    FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
978      super(unfiltered, predicate);
979    }
980
981    @Override
982    public Comparator<? super E> comparator() {
983      return ((SortedSet<E>) unfiltered).comparator();
984    }
985
986    @Override
987    public SortedSet<E> subSet(E fromElement, E toElement) {
988      return new FilteredSortedSet<E>(
989          ((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate);
990    }
991
992    @Override
993    public SortedSet<E> headSet(E toElement) {
994      return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
995    }
996
997    @Override
998    public SortedSet<E> tailSet(E fromElement) {
999      return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
1000    }
1001
1002    @Override
1003    public E first() {
1004      return iterator().next();
1005    }
1006
1007    @Override
1008    public E last() {
1009      SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
1010      while (true) {
1011        E element = sortedUnfiltered.last();
1012        if (predicate.apply(element)) {
1013          return element;
1014        }
1015        sortedUnfiltered = sortedUnfiltered.headSet(element);
1016      }
1017    }
1018  }
1019
1020  /**
1021   * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that
1022   * satisfy a predicate. The returned set is a live view of {@code unfiltered};
1023   * changes to one affect the other.
1024   *
1025   * <p>The resulting set's iterator does not support {@code remove()}, but all
1026   * other set methods are supported. When given an element that doesn't satisfy
1027   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
1028   * an {@link IllegalArgumentException}. When methods such as
1029   * {@code removeAll()} and {@code clear()} are called on the filtered set,
1030   * only elements that satisfy the filter will be removed from the underlying
1031   * set.
1032   *
1033   * <p>The returned set isn't threadsafe or serializable, even if
1034   * {@code unfiltered} is.
1035   *
1036   * <p>Many of the filtered set's methods, such as {@code size()}, iterate across
1037   * every element in the underlying set and determine which elements satisfy
1038   * the filter. When a live view is <i>not</i> needed, it may be faster to copy
1039   * {@code Iterables.filter(unfiltered, predicate)} and use the copy.
1040   *
1041   * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
1042   * as documented at {@link Predicate#apply}. Do not provide a predicate such as
1043   * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
1044   * equals. (See {@link Iterables#filter(Iterable, Class)} for related
1045   * functionality.)
1046   *
1047   * @since 14.0
1048   */
1049  @GwtIncompatible // NavigableSet
1050  @SuppressWarnings("unchecked")
1051  public static <E> NavigableSet<E> filter(
1052      NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
1053    if (unfiltered instanceof FilteredSet) {
1054      // Support clear(), removeAll(), and retainAll() when filtering a filtered
1055      // collection.
1056      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
1057      Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate);
1058      return new FilteredNavigableSet<E>((NavigableSet<E>) filtered.unfiltered, combinedPredicate);
1059    }
1060
1061    return new FilteredNavigableSet<E>(checkNotNull(unfiltered), checkNotNull(predicate));
1062  }
1063
1064  @GwtIncompatible // NavigableSet
1065  private static class FilteredNavigableSet<E> extends FilteredSortedSet<E>
1066      implements NavigableSet<E> {
1067    FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
1068      super(unfiltered, predicate);
1069    }
1070
1071    NavigableSet<E> unfiltered() {
1072      return (NavigableSet<E>) unfiltered;
1073    }
1074
1075    @Override
1076    @Nullable
1077    public E lower(E e) {
1078      return Iterators.getNext(headSet(e, false).descendingIterator(), null);
1079    }
1080
1081    @Override
1082    @Nullable
1083    public E floor(E e) {
1084      return Iterators.getNext(headSet(e, true).descendingIterator(), null);
1085    }
1086
1087    @Override
1088    public E ceiling(E e) {
1089      return Iterables.getFirst(tailSet(e, true), null);
1090    }
1091
1092    @Override
1093    public E higher(E e) {
1094      return Iterables.getFirst(tailSet(e, false), null);
1095    }
1096
1097    @Override
1098    public E pollFirst() {
1099      return Iterables.removeFirstMatching(unfiltered(), predicate);
1100    }
1101
1102    @Override
1103    public E pollLast() {
1104      return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate);
1105    }
1106
1107    @Override
1108    public NavigableSet<E> descendingSet() {
1109      return Sets.filter(unfiltered().descendingSet(), predicate);
1110    }
1111
1112    @Override
1113    public Iterator<E> descendingIterator() {
1114      return Iterators.filter(unfiltered().descendingIterator(), predicate);
1115    }
1116
1117    @Override
1118    public E last() {
1119      return descendingIterator().next();
1120    }
1121
1122    @Override
1123    public NavigableSet<E> subSet(
1124        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
1125      return filter(
1126          unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate);
1127    }
1128
1129    @Override
1130    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1131      return filter(unfiltered().headSet(toElement, inclusive), predicate);
1132    }
1133
1134    @Override
1135    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1136      return filter(unfiltered().tailSet(fromElement, inclusive), predicate);
1137    }
1138  }
1139
1140  /**
1141   * Returns every possible list that can be formed by choosing one element
1142   * from each of the given sets in order; the "n-ary
1143   * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
1144   * product</a>" of the sets. For example: <pre>   {@code
1145   *
1146   *   Sets.cartesianProduct(ImmutableList.of(
1147   *       ImmutableSet.of(1, 2),
1148   *       ImmutableSet.of("A", "B", "C")))}</pre>
1149   *
1150   * <p>returns a set containing six lists:
1151   *
1152   * <ul>
1153   * <li>{@code ImmutableList.of(1, "A")}
1154   * <li>{@code ImmutableList.of(1, "B")}
1155   * <li>{@code ImmutableList.of(1, "C")}
1156   * <li>{@code ImmutableList.of(2, "A")}
1157   * <li>{@code ImmutableList.of(2, "B")}
1158   * <li>{@code ImmutableList.of(2, "C")}
1159   * </ul>
1160   *
1161   * <p>The result is guaranteed to be in the "traditional", lexicographical
1162   * order for Cartesian products that you would get from nesting for loops:
1163   * <pre>   {@code
1164   *
1165   *   for (B b0 : sets.get(0)) {
1166   *     for (B b1 : sets.get(1)) {
1167   *       ...
1168   *       ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
1169   *       // operate on tuple
1170   *     }
1171   *   }}</pre>
1172   *
1173   * <p>Note that if any input set is empty, the Cartesian product will also be
1174   * empty. If no sets at all are provided (an empty list), the resulting
1175   * Cartesian product has one element, an empty list (counter-intuitive, but
1176   * mathematically consistent).
1177   *
1178   * <p><i>Performance notes:</i> while the cartesian product of sets of size
1179   * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
1180   * consumption is much smaller. When the cartesian set is constructed, the
1181   * input sets are merely copied. Only as the resulting set is iterated are the
1182   * individual lists created, and these are not retained after iteration.
1183   *
1184   * @param sets the sets to choose elements from, in the order that
1185   *     the elements chosen from those sets should appear in the resulting
1186   *     lists
1187   * @param <B> any common base class shared by all axes (often just {@link
1188   *     Object})
1189   * @return the Cartesian product, as an immutable set containing immutable
1190   *     lists
1191   * @throws NullPointerException if {@code sets}, any one of the {@code sets},
1192   *     or any element of a provided set is null
1193   * @since 2.0
1194   */
1195  public static <B> Set<List<B>> cartesianProduct(List<? extends Set<? extends B>> sets) {
1196    return CartesianSet.create(sets);
1197  }
1198
1199  /**
1200   * Returns every possible list that can be formed by choosing one element
1201   * from each of the given sets in order; the "n-ary
1202   * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
1203   * product</a>" of the sets. For example: <pre>   {@code
1204   *
1205   *   Sets.cartesianProduct(
1206   *       ImmutableSet.of(1, 2),
1207   *       ImmutableSet.of("A", "B", "C"))}</pre>
1208   *
1209   * <p>returns a set containing six lists:
1210   *
1211   * <ul>
1212   * <li>{@code ImmutableList.of(1, "A")}
1213   * <li>{@code ImmutableList.of(1, "B")}
1214   * <li>{@code ImmutableList.of(1, "C")}
1215   * <li>{@code ImmutableList.of(2, "A")}
1216   * <li>{@code ImmutableList.of(2, "B")}
1217   * <li>{@code ImmutableList.of(2, "C")}
1218   * </ul>
1219   *
1220   * <p>The result is guaranteed to be in the "traditional", lexicographical
1221   * order for Cartesian products that you would get from nesting for loops:
1222   * <pre>   {@code
1223   *
1224   *   for (B b0 : sets.get(0)) {
1225   *     for (B b1 : sets.get(1)) {
1226   *       ...
1227   *       ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
1228   *       // operate on tuple
1229   *     }
1230   *   }}</pre>
1231   *
1232   * <p>Note that if any input set is empty, the Cartesian product will also be
1233   * empty. If no sets at all are provided (an empty list), the resulting
1234   * Cartesian product has one element, an empty list (counter-intuitive, but
1235   * mathematically consistent).
1236   *
1237   * <p><i>Performance notes:</i> while the cartesian product of sets of size
1238   * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
1239   * consumption is much smaller. When the cartesian set is constructed, the
1240   * input sets are merely copied. Only as the resulting set is iterated are the
1241   * individual lists created, and these are not retained after iteration.
1242   *
1243   * @param sets the sets to choose elements from, in the order that
1244   *     the elements chosen from those sets should appear in the resulting
1245   *     lists
1246   * @param <B> any common base class shared by all axes (often just {@link
1247   *     Object})
1248   * @return the Cartesian product, as an immutable set containing immutable
1249   *     lists
1250   * @throws NullPointerException if {@code sets}, any one of the {@code sets},
1251   *     or any element of a provided set is null
1252   * @since 2.0
1253   */
1254  public static <B> Set<List<B>> cartesianProduct(Set<? extends B>... sets) {
1255    return cartesianProduct(Arrays.asList(sets));
1256  }
1257
1258  private static final class CartesianSet<E> extends ForwardingCollection<List<E>>
1259      implements Set<List<E>> {
1260    private final transient ImmutableList<ImmutableSet<E>> axes;
1261    private final transient CartesianList<E> delegate;
1262
1263    static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) {
1264      ImmutableList.Builder<ImmutableSet<E>> axesBuilder =
1265          new ImmutableList.Builder<ImmutableSet<E>>(sets.size());
1266      for (Set<? extends E> set : sets) {
1267        ImmutableSet<E> copy = ImmutableSet.copyOf(set);
1268        if (copy.isEmpty()) {
1269          return ImmutableSet.of();
1270        }
1271        axesBuilder.add(copy);
1272      }
1273      final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
1274      ImmutableList<List<E>> listAxes =
1275          new ImmutableList<List<E>>() {
1276            @Override
1277            public int size() {
1278              return axes.size();
1279            }
1280
1281            @Override
1282            public List<E> get(int index) {
1283              return axes.get(index).asList();
1284            }
1285
1286            @Override
1287            boolean isPartialView() {
1288              return true;
1289            }
1290          };
1291      return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
1292    }
1293
1294    private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
1295      this.axes = axes;
1296      this.delegate = delegate;
1297    }
1298
1299    @Override
1300    protected Collection<List<E>> delegate() {
1301      return delegate;
1302    }
1303
1304    @Override
1305    public boolean equals(@Nullable Object object) {
1306      // Warning: this is broken if size() == 0, so it is critical that we
1307      // substitute an empty ImmutableSet to the user in place of this
1308      if (object instanceof CartesianSet) {
1309        CartesianSet<?> that = (CartesianSet<?>) object;
1310        return this.axes.equals(that.axes);
1311      }
1312      return super.equals(object);
1313    }
1314
1315    @Override
1316    public int hashCode() {
1317      // Warning: this is broken if size() == 0, so it is critical that we
1318      // substitute an empty ImmutableSet to the user in place of this
1319
1320      // It's a weird formula, but tests prove it works.
1321      int adjust = size() - 1;
1322      for (int i = 0; i < axes.size(); i++) {
1323        adjust *= 31;
1324        adjust = ~~adjust;
1325        // in GWT, we have to deal with integer overflow carefully
1326      }
1327      int hash = 1;
1328      for (Set<E> axis : axes) {
1329        hash = 31 * hash + (size() / axis.size() * axis.hashCode());
1330
1331        hash = ~~hash;
1332      }
1333      hash += adjust;
1334      return ~~hash;
1335    }
1336  }
1337
1338  /**
1339   * Returns the set of all possible subsets of {@code set}. For example,
1340   * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
1341   * {1}, {2}, {1, 2}}}.
1342   *
1343   * <p>Elements appear in these subsets in the same iteration order as they
1344   * appeared in the input set. The order in which these subsets appear in the
1345   * outer set is undefined. Note that the power set of the empty set is not the
1346   * empty set, but a one-element set containing the empty set.
1347   *
1348   * <p>The returned set and its constituent sets use {@code equals} to decide
1349   * whether two elements are identical, even if the input set uses a different
1350   * concept of equivalence.
1351   *
1352   * <p><i>Performance notes:</i> while the power set of a set with size {@code
1353   * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
1354   * power set is constructed, the input set is merely copied. Only as the
1355   * power set is iterated are the individual subsets created, and these subsets
1356   * themselves occupy only a small constant amount of memory.
1357   *
1358   * @param set the set of elements to construct a power set from
1359   * @return the power set, as an immutable set of immutable sets
1360   * @throws IllegalArgumentException if {@code set} has more than 30 unique
1361   *     elements (causing the power set size to exceed the {@code int} range)
1362   * @throws NullPointerException if {@code set} is or contains {@code null}
1363   * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at
1364   *      Wikipedia</a>
1365   * @since 4.0
1366   */
1367  @GwtCompatible(serializable = false)
1368  public static <E> Set<Set<E>> powerSet(Set<E> set) {
1369    return new PowerSet<E>(set);
1370  }
1371
1372  private static final class SubSet<E> extends AbstractSet<E> {
1373    private final ImmutableMap<E, Integer> inputSet;
1374    private final int mask;
1375
1376    SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
1377      this.inputSet = inputSet;
1378      this.mask = mask;
1379    }
1380
1381    @Override
1382    public Iterator<E> iterator() {
1383      return new UnmodifiableIterator<E>() {
1384        final ImmutableList<E> elements = inputSet.keySet().asList();
1385        int remainingSetBits = mask;
1386
1387        @Override
1388        public boolean hasNext() {
1389          return remainingSetBits != 0;
1390        }
1391
1392        @Override
1393        public E next() {
1394          int index = Integer.numberOfTrailingZeros(remainingSetBits);
1395          if (index == 32) {
1396            throw new NoSuchElementException();
1397          }
1398          remainingSetBits &= ~(1 << index);
1399          return elements.get(index);
1400        }
1401      };
1402    }
1403
1404    @Override
1405    public int size() {
1406      return Integer.bitCount(mask);
1407    }
1408
1409    @Override
1410    public boolean contains(@Nullable Object o) {
1411      Integer index = inputSet.get(o);
1412      return index != null && (mask & (1 << index)) != 0;
1413    }
1414  }
1415
1416  private static final class PowerSet<E> extends AbstractSet<Set<E>> {
1417    final ImmutableMap<E, Integer> inputSet;
1418
1419    PowerSet(Set<E> input) {
1420      this.inputSet = Maps.indexMap(input);
1421      checkArgument(
1422          inputSet.size() <= 30, "Too many elements to create power set: %s > 30", inputSet.size());
1423    }
1424
1425    @Override
1426    public int size() {
1427      return 1 << inputSet.size();
1428    }
1429
1430    @Override
1431    public boolean isEmpty() {
1432      return false;
1433    }
1434
1435    @Override
1436    public Iterator<Set<E>> iterator() {
1437      return new AbstractIndexedListIterator<Set<E>>(size()) {
1438        @Override
1439        protected Set<E> get(final int setBits) {
1440          return new SubSet<E>(inputSet, setBits);
1441        }
1442      };
1443    }
1444
1445    @Override
1446    public boolean contains(@Nullable Object obj) {
1447      if (obj instanceof Set) {
1448        Set<?> set = (Set<?>) obj;
1449        return inputSet.keySet().containsAll(set);
1450      }
1451      return false;
1452    }
1453
1454    @Override
1455    public boolean equals(@Nullable Object obj) {
1456      if (obj instanceof PowerSet) {
1457        PowerSet<?> that = (PowerSet<?>) obj;
1458        return inputSet.equals(that.inputSet);
1459      }
1460      return super.equals(obj);
1461    }
1462
1463    @Override
1464    public int hashCode() {
1465      /*
1466       * The sum of the sums of the hash codes in each subset is just the sum of
1467       * each input element's hash code times the number of sets that element
1468       * appears in. Each element appears in exactly half of the 2^n sets, so:
1469       */
1470      return inputSet.keySet().hashCode() << (inputSet.size() - 1);
1471    }
1472
1473    @Override
1474    public String toString() {
1475      return "powerSet(" + inputSet + ")";
1476    }
1477  }
1478
1479  /**
1480   * An implementation for {@link Set#hashCode()}.
1481   */
1482  static int hashCodeImpl(Set<?> s) {
1483    int hashCode = 0;
1484    for (Object o : s) {
1485      hashCode += o != null ? o.hashCode() : 0;
1486
1487      hashCode = ~~hashCode;
1488      // Needed to deal with unusual integer overflow in GWT.
1489    }
1490    return hashCode;
1491  }
1492
1493  /**
1494   * An implementation for {@link Set#equals(Object)}.
1495   */
1496  static boolean equalsImpl(Set<?> s, @Nullable Object object) {
1497    if (s == object) {
1498      return true;
1499    }
1500    if (object instanceof Set) {
1501      Set<?> o = (Set<?>) object;
1502
1503      try {
1504        return s.size() == o.size() && s.containsAll(o);
1505      } catch (NullPointerException ignored) {
1506        return false;
1507      } catch (ClassCastException ignored) {
1508        return false;
1509      }
1510    }
1511    return false;
1512  }
1513
1514  /**
1515   * Returns an unmodifiable view of the specified navigable set. This method
1516   * allows modules to provide users with "read-only" access to internal
1517   * navigable sets. Query operations on the returned set "read through" to the
1518   * specified set, and attempts to modify the returned set, whether direct or
1519   * via its collection views, result in an
1520   * {@code UnsupportedOperationException}.
1521   *
1522   * <p>The returned navigable set will be serializable if the specified
1523   * navigable set is serializable.
1524   *
1525   * @param set the navigable set for which an unmodifiable view is to be
1526   *        returned
1527   * @return an unmodifiable view of the specified navigable set
1528   * @since 12.0
1529   */
1530  public static <E> NavigableSet<E> unmodifiableNavigableSet(NavigableSet<E> set) {
1531    if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) {
1532      return set;
1533    }
1534    return new UnmodifiableNavigableSet<E>(set);
1535  }
1536
1537  static final class UnmodifiableNavigableSet<E> extends ForwardingSortedSet<E>
1538      implements NavigableSet<E>, Serializable {
1539    private final NavigableSet<E> delegate;
1540
1541    UnmodifiableNavigableSet(NavigableSet<E> delegate) {
1542      this.delegate = checkNotNull(delegate);
1543    }
1544
1545    @Override
1546    protected SortedSet<E> delegate() {
1547      return Collections.unmodifiableSortedSet(delegate);
1548    }
1549
1550    @Override
1551    public E lower(E e) {
1552      return delegate.lower(e);
1553    }
1554
1555    @Override
1556    public E floor(E e) {
1557      return delegate.floor(e);
1558    }
1559
1560    @Override
1561    public E ceiling(E e) {
1562      return delegate.ceiling(e);
1563    }
1564
1565    @Override
1566    public E higher(E e) {
1567      return delegate.higher(e);
1568    }
1569
1570    @Override
1571    public E pollFirst() {
1572      throw new UnsupportedOperationException();
1573    }
1574
1575    @Override
1576    public E pollLast() {
1577      throw new UnsupportedOperationException();
1578    }
1579
1580    private transient UnmodifiableNavigableSet<E> descendingSet;
1581
1582    @Override
1583    public NavigableSet<E> descendingSet() {
1584      UnmodifiableNavigableSet<E> result = descendingSet;
1585      if (result == null) {
1586        result = descendingSet = new UnmodifiableNavigableSet<E>(delegate.descendingSet());
1587        result.descendingSet = this;
1588      }
1589      return result;
1590    }
1591
1592    @Override
1593    public Iterator<E> descendingIterator() {
1594      return Iterators.unmodifiableIterator(delegate.descendingIterator());
1595    }
1596
1597    @Override
1598    public NavigableSet<E> subSet(
1599        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
1600      return unmodifiableNavigableSet(
1601          delegate.subSet(fromElement, fromInclusive, toElement, toInclusive));
1602    }
1603
1604    @Override
1605    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1606      return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive));
1607    }
1608
1609    @Override
1610    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1611      return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive));
1612    }
1613
1614    private static final long serialVersionUID = 0;
1615  }
1616
1617  /**
1618   * Returns a synchronized (thread-safe) navigable set backed by the specified
1619   * navigable set.  In order to guarantee serial access, it is critical that
1620   * <b>all</b> access to the backing navigable set is accomplished
1621   * through the returned navigable set (or its views).
1622   *
1623   * <p>It is imperative that the user manually synchronize on the returned
1624   * sorted set when iterating over it or any of its {@code descendingSet},
1625   * {@code subSet}, {@code headSet}, or {@code tailSet} views. <pre>   {@code
1626   *
1627   *   NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
1628   *    ...
1629   *   synchronized (set) {
1630   *     // Must be in the synchronized block
1631   *     Iterator<E> it = set.iterator();
1632   *     while (it.hasNext()) {
1633   *       foo(it.next());
1634   *     }
1635   *   }}</pre>
1636   *
1637   * <p>or: <pre>   {@code
1638   *
1639   *   NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
1640   *   NavigableSet<E> set2 = set.descendingSet().headSet(foo);
1641   *    ...
1642   *   synchronized (set) { // Note: set, not set2!!!
1643   *     // Must be in the synchronized block
1644   *     Iterator<E> it = set2.descendingIterator();
1645   *     while (it.hasNext())
1646   *       foo(it.next());
1647   *     }
1648   *   }}</pre>
1649   *
1650   * <p>Failure to follow this advice may result in non-deterministic behavior.
1651   *
1652   * <p>The returned navigable set will be serializable if the specified
1653   * navigable set is serializable.
1654   *
1655   * @param navigableSet the navigable set to be "wrapped" in a synchronized
1656   *    navigable set.
1657   * @return a synchronized view of the specified navigable set.
1658   * @since 13.0
1659   */
1660  @GwtIncompatible // NavigableSet
1661  public static <E> NavigableSet<E> synchronizedNavigableSet(NavigableSet<E> navigableSet) {
1662    return Synchronized.navigableSet(navigableSet);
1663  }
1664
1665  /**
1666   * Remove each element in an iterable from a set.
1667   */
1668  static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
1669    boolean changed = false;
1670    while (iterator.hasNext()) {
1671      changed |= set.remove(iterator.next());
1672    }
1673    return changed;
1674  }
1675
1676  static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
1677    checkNotNull(collection); // for GWT
1678    if (collection instanceof Multiset) {
1679      collection = ((Multiset<?>) collection).elementSet();
1680    }
1681    /*
1682     * AbstractSet.removeAll(List) has quadratic behavior if the list size
1683     * is just less than the set's size.  We augment the test by
1684     * assuming that sets have fast contains() performance, and other
1685     * collections don't.  See
1686     * http://code.google.com/p/guava-libraries/issues/detail?id=1013
1687     */
1688    if (collection instanceof Set && collection.size() > set.size()) {
1689      return Iterators.removeAll(set.iterator(), collection);
1690    } else {
1691      return removeAllImpl(set, collection.iterator());
1692    }
1693  }
1694
1695  @GwtIncompatible // NavigableSet
1696  static class DescendingSet<E> extends ForwardingNavigableSet<E> {
1697    private final NavigableSet<E> forward;
1698
1699    DescendingSet(NavigableSet<E> forward) {
1700      this.forward = forward;
1701    }
1702
1703    @Override
1704    protected NavigableSet<E> delegate() {
1705      return forward;
1706    }
1707
1708    @Override
1709    public E lower(E e) {
1710      return forward.higher(e);
1711    }
1712
1713    @Override
1714    public E floor(E e) {
1715      return forward.ceiling(e);
1716    }
1717
1718    @Override
1719    public E ceiling(E e) {
1720      return forward.floor(e);
1721    }
1722
1723    @Override
1724    public E higher(E e) {
1725      return forward.lower(e);
1726    }
1727
1728    @Override
1729    public E pollFirst() {
1730      return forward.pollLast();
1731    }
1732
1733    @Override
1734    public E pollLast() {
1735      return forward.pollFirst();
1736    }
1737
1738    @Override
1739    public NavigableSet<E> descendingSet() {
1740      return forward;
1741    }
1742
1743    @Override
1744    public Iterator<E> descendingIterator() {
1745      return forward.iterator();
1746    }
1747
1748    @Override
1749    public NavigableSet<E> subSet(
1750        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
1751      return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
1752    }
1753
1754    @Override
1755    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1756      return forward.tailSet(toElement, inclusive).descendingSet();
1757    }
1758
1759    @Override
1760    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1761      return forward.headSet(fromElement, inclusive).descendingSet();
1762    }
1763
1764    @SuppressWarnings("unchecked")
1765    @Override
1766    public Comparator<? super E> comparator() {
1767      Comparator<? super E> forwardComparator = forward.comparator();
1768      if (forwardComparator == null) {
1769        return (Comparator) Ordering.natural().reverse();
1770      } else {
1771        return reverse(forwardComparator);
1772      }
1773    }
1774
1775    // If we inline this, we get a javac error.
1776    private static <T> Ordering<T> reverse(Comparator<T> forward) {
1777      return Ordering.from(forward).reverse();
1778    }
1779
1780    @Override
1781    public E first() {
1782      return forward.last();
1783    }
1784
1785    @Override
1786    public SortedSet<E> headSet(E toElement) {
1787      return standardHeadSet(toElement);
1788    }
1789
1790    @Override
1791    public E last() {
1792      return forward.first();
1793    }
1794
1795    @Override
1796    public SortedSet<E> subSet(E fromElement, E toElement) {
1797      return standardSubSet(fromElement, toElement);
1798    }
1799
1800    @Override
1801    public SortedSet<E> tailSet(E fromElement) {
1802      return standardTailSet(fromElement);
1803    }
1804
1805    @Override
1806    public Iterator<E> iterator() {
1807      return forward.descendingIterator();
1808    }
1809
1810    @Override
1811    public Object[] toArray() {
1812      return standardToArray();
1813    }
1814
1815    @Override
1816    public <T> T[] toArray(T[] array) {
1817      return standardToArray(array);
1818    }
1819
1820    @Override
1821    public String toString() {
1822      return standardToString();
1823    }
1824  }
1825
1826  /**
1827   * Returns a view of the portion of {@code set} whose elements are contained by {@code range}.
1828   *
1829   * <p>This method delegates to the appropriate methods of {@link NavigableSet} (namely
1830   * {@link NavigableSet#subSet(Object, boolean, Object, boolean) subSet()},
1831   * {@link NavigableSet#tailSet(Object, boolean) tailSet()}, and
1832   * {@link NavigableSet#headSet(Object, boolean) headSet()}) to actually construct the view.
1833   * Consult these methods for a full description of the returned view's behavior.
1834   *
1835   * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
1836   * ordering. {@code NavigableSet} on the other hand can specify a custom ordering via a
1837   * {@link Comparator}, which can violate the natural ordering. Using this method (or in general
1838   * using {@code Range}) with unnaturally-ordered sets can lead to unexpected and undefined
1839   * behavior.
1840   *
1841   * @since 20.0
1842   */
1843  @Beta
1844  @GwtIncompatible // NavigableSet
1845  public static <K extends Comparable<? super K>> NavigableSet<K> subSet(
1846      NavigableSet<K> set, Range<K> range) {
1847    if (set.comparator() != null
1848        && set.comparator() != Ordering.natural()
1849        && range.hasLowerBound()
1850        && range.hasUpperBound()) {
1851      checkArgument(
1852          set.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
1853          "set is using a custom comparator which is inconsistent with the natural ordering.");
1854    }
1855    if (range.hasLowerBound() && range.hasUpperBound()) {
1856      return set.subSet(
1857          range.lowerEndpoint(),
1858          range.lowerBoundType() == BoundType.CLOSED,
1859          range.upperEndpoint(),
1860          range.upperBoundType() == BoundType.CLOSED);
1861    } else if (range.hasLowerBound()) {
1862      return set.tailSet(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
1863    } else if (range.hasUpperBound()) {
1864      return set.headSet(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
1865    }
1866    return checkNotNull(set);
1867  }
1868}