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