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