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 =
1333          new ImmutableList.Builder<ImmutableSet<E>>(sets.size());
1334      for (Set<? extends E> set : sets) {
1335        ImmutableSet<E> copy = ImmutableSet.copyOf(set);
1336        if (copy.isEmpty()) {
1337          return ImmutableSet.of();
1338        }
1339        axesBuilder.add(copy);
1340      }
1341      final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
1342      ImmutableList<List<E>> listAxes =
1343          new ImmutableList<List<E>>() {
1344            @Override
1345            public int size() {
1346              return axes.size();
1347            }
1348
1349            @Override
1350            public List<E> get(int index) {
1351              return axes.get(index).asList();
1352            }
1353
1354            @Override
1355            boolean isPartialView() {
1356              return true;
1357            }
1358          };
1359      return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
1360    }
1361
1362    private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
1363      this.axes = axes;
1364      this.delegate = delegate;
1365    }
1366
1367    @Override
1368    protected Collection<List<E>> delegate() {
1369      return delegate;
1370    }
1371
1372    @Override
1373    public boolean equals(@Nullable Object object) {
1374      // Warning: this is broken if size() == 0, so it is critical that we
1375      // substitute an empty ImmutableSet to the user in place of this
1376      if (object instanceof CartesianSet) {
1377        CartesianSet<?> that = (CartesianSet<?>) object;
1378        return this.axes.equals(that.axes);
1379      }
1380      return super.equals(object);
1381    }
1382
1383    @Override
1384    public int hashCode() {
1385      // Warning: this is broken if size() == 0, so it is critical that we
1386      // substitute an empty ImmutableSet to the user in place of this
1387
1388      // It's a weird formula, but tests prove it works.
1389      int adjust = size() - 1;
1390      for (int i = 0; i < axes.size(); i++) {
1391        adjust *= 31;
1392        adjust = ~~adjust;
1393        // in GWT, we have to deal with integer overflow carefully
1394      }
1395      int hash = 1;
1396      for (Set<E> axis : axes) {
1397        hash = 31 * hash + (size() / axis.size() * axis.hashCode());
1398
1399        hash = ~~hash;
1400      }
1401      hash += adjust;
1402      return ~~hash;
1403    }
1404  }
1405
1406  /**
1407   * Returns the set of all possible subsets of {@code set}. For example,
1408   * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
1409   * {1}, {2}, {1, 2}}}.
1410   *
1411   * <p>Elements appear in these subsets in the same iteration order as they
1412   * appeared in the input set. The order in which these subsets appear in the
1413   * outer set is undefined. Note that the power set of the empty set is not the
1414   * empty set, but a one-element set containing the empty set.
1415   *
1416   * <p>The returned set and its constituent sets use {@code equals} to decide
1417   * whether two elements are identical, even if the input set uses a different
1418   * concept of equivalence.
1419   *
1420   * <p><i>Performance notes:</i> while the power set of a set with size {@code
1421   * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
1422   * power set is constructed, the input set is merely copied. Only as the
1423   * power set is iterated are the individual subsets created, and these subsets
1424   * themselves occupy only a small constant amount of memory.
1425   *
1426   * @param set the set of elements to construct a power set from
1427   * @return the power set, as an immutable set of immutable sets
1428   * @throws IllegalArgumentException if {@code set} has more than 30 unique
1429   *     elements (causing the power set size to exceed the {@code int} range)
1430   * @throws NullPointerException if {@code set} is or contains {@code null}
1431   * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at
1432   *      Wikipedia</a>
1433   * @since 4.0
1434   */
1435  @GwtCompatible(serializable = false)
1436  public static <E> Set<Set<E>> powerSet(Set<E> set) {
1437    return new PowerSet<E>(set);
1438  }
1439
1440  private static final class SubSet<E> extends AbstractSet<E> {
1441    private final ImmutableMap<E, Integer> inputSet;
1442    private final int mask;
1443
1444    SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
1445      this.inputSet = inputSet;
1446      this.mask = mask;
1447    }
1448
1449    @Override
1450    public Iterator<E> iterator() {
1451      return new UnmodifiableIterator<E>() {
1452        final ImmutableList<E> elements = inputSet.keySet().asList();
1453        int remainingSetBits = mask;
1454
1455        @Override
1456        public boolean hasNext() {
1457          return remainingSetBits != 0;
1458        }
1459
1460        @Override
1461        public E next() {
1462          int index = Integer.numberOfTrailingZeros(remainingSetBits);
1463          if (index == 32) {
1464            throw new NoSuchElementException();
1465          }
1466          remainingSetBits &= ~(1 << index);
1467          return elements.get(index);
1468        }
1469      };
1470    }
1471
1472    @Override
1473    public int size() {
1474      return Integer.bitCount(mask);
1475    }
1476
1477    @Override
1478    public boolean contains(@Nullable Object o) {
1479      Integer index = inputSet.get(o);
1480      return index != null && (mask & (1 << index)) != 0;
1481    }
1482  }
1483
1484  private static final class PowerSet<E> extends AbstractSet<Set<E>> {
1485    final ImmutableMap<E, Integer> inputSet;
1486
1487    PowerSet(Set<E> input) {
1488      this.inputSet = Maps.indexMap(input);
1489      checkArgument(
1490          inputSet.size() <= 30, "Too many elements to create power set: %s > 30", inputSet.size());
1491    }
1492
1493    @Override
1494    public int size() {
1495      return 1 << inputSet.size();
1496    }
1497
1498    @Override
1499    public boolean isEmpty() {
1500      return false;
1501    }
1502
1503    @Override
1504    public Iterator<Set<E>> iterator() {
1505      return new AbstractIndexedListIterator<Set<E>>(size()) {
1506        @Override
1507        protected Set<E> get(final int setBits) {
1508          return new SubSet<E>(inputSet, setBits);
1509        }
1510      };
1511    }
1512
1513    @Override
1514    public boolean contains(@Nullable Object obj) {
1515      if (obj instanceof Set) {
1516        Set<?> set = (Set<?>) obj;
1517        return inputSet.keySet().containsAll(set);
1518      }
1519      return false;
1520    }
1521
1522    @Override
1523    public boolean equals(@Nullable Object obj) {
1524      if (obj instanceof PowerSet) {
1525        PowerSet<?> that = (PowerSet<?>) obj;
1526        return inputSet.equals(that.inputSet);
1527      }
1528      return super.equals(obj);
1529    }
1530
1531    @Override
1532    public int hashCode() {
1533      /*
1534       * The sum of the sums of the hash codes in each subset is just the sum of
1535       * each input element's hash code times the number of sets that element
1536       * appears in. Each element appears in exactly half of the 2^n sets, so:
1537       */
1538      return inputSet.keySet().hashCode() << (inputSet.size() - 1);
1539    }
1540
1541    @Override
1542    public String toString() {
1543      return "powerSet(" + inputSet + ")";
1544    }
1545  }
1546
1547  /**
1548   * Returns the set of all subsets of {@code set} of size {@code size}. For example, {@code
1549   * combinations(ImmutableSet.of(1, 2, 3), 2)} returns the set {@code {{1, 2}, {1, 3}, {2, 3}}}.
1550   *
1551   * <p>Elements appear in these subsets in the same iteration order as they appeared in the input
1552   * set. The order in which these subsets appear in the outer set is undefined.
1553   *
1554   * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements
1555   * are identical, even if the input set uses a different concept of equivalence.
1556   *
1557   * <p><i>Performance notes:</i> the memory usage of the returned set is only {@code O(n)}. When
1558   * the result set is constructed, the input set is merely copied. Only as the result set is
1559   * iterated are the individual subsets created. Each of these subsets occupies an additional O(n)
1560   * memory but only for as long as the user retains a reference to it. That is, the set returned by
1561   * {@code combinations} does not retain the individual subsets.
1562   *
1563   * @param set the set of elements to take combinations of
1564   * @param size the number of elements per combination
1565   * @return the set of all combinations of {@code size} elements from {@code set}
1566   * @throws IllegalArgumentException if {@code size} is not between 0 and {@code set.size()}
1567   *     inclusive
1568   * @throws NullPointerException if {@code set} is or contains {@code null}
1569   * @since 23.0
1570   */
1571  @Beta
1572  public static <E> Set<Set<E>> combinations(Set<E> set, final int size) {
1573    final ImmutableMap<E, Integer> index = Maps.indexMap(set);
1574    checkNonnegative(size, "size");
1575    checkArgument(size <= index.size(), "size (%s) must be <= set.size() (%s)", size, index.size());
1576    if (size == 0) {
1577      return ImmutableSet.<Set<E>>of(ImmutableSet.<E>of());
1578    } else if (size == index.size()) {
1579      return ImmutableSet.<Set<E>>of(index.keySet());
1580    }
1581    return new AbstractSet<Set<E>>() {
1582      @Override
1583      public boolean contains(@Nullable Object o) {
1584        if (o instanceof Set) {
1585          Set<?> s = (Set<?>) o;
1586          return s.size() == size && index.keySet().containsAll(s);
1587        }
1588        return false;
1589      }
1590
1591      @Override
1592      public Iterator<Set<E>> iterator() {
1593        return new AbstractIterator<Set<E>>() {
1594          final BitSet bits = new BitSet(index.size());
1595
1596          @Override
1597          protected Set<E> computeNext() {
1598            if (bits.isEmpty()) {
1599              bits.set(0, size);
1600            } else {
1601              int firstSetBit = bits.nextSetBit(0);
1602              int bitToFlip = bits.nextClearBit(firstSetBit);
1603
1604              if (bitToFlip == index.size()) {
1605                return endOfData();
1606              }
1607              /*
1608               * The current set in sorted order looks like
1609               * {firstSetBit, firstSetBit + 1, ..., bitToFlip - 1, ...}
1610               * where it does *not* contain bitToFlip.
1611               *
1612               * The next combination is
1613               *
1614               * {0, 1, ..., bitToFlip - firstSetBit - 2, bitToFlip, ...}
1615               *
1616               * This is lexicographically next if you look at the combinations in descending order
1617               * e.g. {2, 1, 0}, {3, 1, 0}, {3, 2, 0}, {3, 2, 1}, {4, 1, 0}...
1618               */
1619
1620              bits.set(0, bitToFlip - firstSetBit - 1);
1621              bits.clear(bitToFlip - firstSetBit - 1, bitToFlip);
1622              bits.set(bitToFlip);
1623            }
1624            final BitSet copy = (BitSet) bits.clone();
1625            return new AbstractSet<E>() {
1626              @Override
1627              public boolean contains(@Nullable Object o) {
1628                Integer i = index.get(o);
1629                return i != null && copy.get(i);
1630              }
1631
1632              @Override
1633              public Iterator<E> iterator() {
1634                return new AbstractIterator<E>() {
1635                  int i = -1;
1636
1637                  @Override
1638                  protected E computeNext() {
1639                    i = copy.nextSetBit(i + 1);
1640                    if (i == -1) {
1641                      return endOfData();
1642                    }
1643                    return index.keySet().asList().get(i);
1644                  }
1645                };
1646              }
1647
1648              @Override
1649              public int size() {
1650                return size;
1651              }
1652            };
1653          }
1654        };
1655      }
1656
1657      @Override
1658      public int size() {
1659        return IntMath.binomial(index.size(), size);
1660      }
1661
1662      @Override
1663      public String toString() {
1664        return "Sets.combinations(" + index.keySet() + ", " + size + ")";
1665      }
1666    };
1667  }
1668
1669  /**
1670   * An implementation for {@link Set#hashCode()}.
1671   */
1672  static int hashCodeImpl(Set<?> s) {
1673    int hashCode = 0;
1674    for (Object o : s) {
1675      hashCode += o != null ? o.hashCode() : 0;
1676
1677      hashCode = ~~hashCode;
1678      // Needed to deal with unusual integer overflow in GWT.
1679    }
1680    return hashCode;
1681  }
1682
1683  /**
1684   * An implementation for {@link Set#equals(Object)}.
1685   */
1686  static boolean equalsImpl(Set<?> s, @Nullable Object object) {
1687    if (s == object) {
1688      return true;
1689    }
1690    if (object instanceof Set) {
1691      Set<?> o = (Set<?>) object;
1692
1693      try {
1694        return s.size() == o.size() && s.containsAll(o);
1695      } catch (NullPointerException ignored) {
1696        return false;
1697      } catch (ClassCastException ignored) {
1698        return false;
1699      }
1700    }
1701    return false;
1702  }
1703
1704  /**
1705   * Returns an unmodifiable view of the specified navigable set. This method
1706   * allows modules to provide users with "read-only" access to internal
1707   * navigable sets. Query operations on the returned set "read through" to the
1708   * specified set, and attempts to modify the returned set, whether direct or
1709   * via its collection views, result in an
1710   * {@code UnsupportedOperationException}.
1711   *
1712   * <p>The returned navigable set will be serializable if the specified
1713   * navigable set is serializable.
1714   *
1715   * @param set the navigable set for which an unmodifiable view is to be
1716   *        returned
1717   * @return an unmodifiable view of the specified navigable set
1718   * @since 12.0
1719   */
1720  public static <E> NavigableSet<E> unmodifiableNavigableSet(NavigableSet<E> set) {
1721    if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) {
1722      return set;
1723    }
1724    return new UnmodifiableNavigableSet<E>(set);
1725  }
1726
1727  static final class UnmodifiableNavigableSet<E> extends ForwardingSortedSet<E>
1728      implements NavigableSet<E>, Serializable {
1729    private final NavigableSet<E> delegate;
1730    private final SortedSet<E> unmodifiableDelegate;
1731
1732    UnmodifiableNavigableSet(NavigableSet<E> delegate) {
1733      this.delegate = checkNotNull(delegate);
1734      this.unmodifiableDelegate = Collections.unmodifiableSortedSet(delegate);
1735    }
1736
1737    @Override
1738    protected SortedSet<E> delegate() {
1739      return unmodifiableDelegate;
1740    }
1741
1742    @Override
1743    public E lower(E e) {
1744      return delegate.lower(e);
1745    }
1746
1747    @Override
1748    public E floor(E e) {
1749      return delegate.floor(e);
1750    }
1751
1752    @Override
1753    public E ceiling(E e) {
1754      return delegate.ceiling(e);
1755    }
1756
1757    @Override
1758    public E higher(E e) {
1759      return delegate.higher(e);
1760    }
1761
1762    @Override
1763    public E pollFirst() {
1764      throw new UnsupportedOperationException();
1765    }
1766
1767    @Override
1768    public E pollLast() {
1769      throw new UnsupportedOperationException();
1770    }
1771
1772    private transient UnmodifiableNavigableSet<E> descendingSet;
1773
1774    @Override
1775    public NavigableSet<E> descendingSet() {
1776      UnmodifiableNavigableSet<E> result = descendingSet;
1777      if (result == null) {
1778        result = descendingSet = new UnmodifiableNavigableSet<E>(delegate.descendingSet());
1779        result.descendingSet = this;
1780      }
1781      return result;
1782    }
1783
1784    @Override
1785    public Iterator<E> descendingIterator() {
1786      return Iterators.unmodifiableIterator(delegate.descendingIterator());
1787    }
1788
1789    @Override
1790    public NavigableSet<E> subSet(
1791        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
1792      return unmodifiableNavigableSet(
1793          delegate.subSet(fromElement, fromInclusive, toElement, toInclusive));
1794    }
1795
1796    @Override
1797    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1798      return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive));
1799    }
1800
1801    @Override
1802    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1803      return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive));
1804    }
1805
1806    private static final long serialVersionUID = 0;
1807  }
1808
1809  /**
1810   * Returns a synchronized (thread-safe) navigable set backed by the specified
1811   * navigable set.  In order to guarantee serial access, it is critical that
1812   * <b>all</b> access to the backing navigable set is accomplished
1813   * through the returned navigable set (or its views).
1814   *
1815   * <p>It is imperative that the user manually synchronize on the returned
1816   * sorted set when iterating over it or any of its {@code descendingSet},
1817   * {@code subSet}, {@code headSet}, or {@code tailSet} views. <pre>   {@code
1818   *
1819   *   NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
1820   *    ...
1821   *   synchronized (set) {
1822   *     // Must be in the synchronized block
1823   *     Iterator<E> it = set.iterator();
1824   *     while (it.hasNext()) {
1825   *       foo(it.next());
1826   *     }
1827   *   }}</pre>
1828   *
1829   * <p>or: <pre>   {@code
1830   *
1831   *   NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
1832   *   NavigableSet<E> set2 = set.descendingSet().headSet(foo);
1833   *    ...
1834   *   synchronized (set) { // Note: set, not set2!!!
1835   *     // Must be in the synchronized block
1836   *     Iterator<E> it = set2.descendingIterator();
1837   *     while (it.hasNext())
1838   *       foo(it.next());
1839   *     }
1840   *   }}</pre>
1841   *
1842   * <p>Failure to follow this advice may result in non-deterministic behavior.
1843   *
1844   * <p>The returned navigable set will be serializable if the specified
1845   * navigable set is serializable.
1846   *
1847   * @param navigableSet the navigable set to be "wrapped" in a synchronized
1848   *    navigable set.
1849   * @return a synchronized view of the specified navigable set.
1850   * @since 13.0
1851   */
1852  @GwtIncompatible // NavigableSet
1853  public static <E> NavigableSet<E> synchronizedNavigableSet(NavigableSet<E> navigableSet) {
1854    return Synchronized.navigableSet(navigableSet);
1855  }
1856
1857  /**
1858   * Remove each element in an iterable from a set.
1859   */
1860  static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
1861    boolean changed = false;
1862    while (iterator.hasNext()) {
1863      changed |= set.remove(iterator.next());
1864    }
1865    return changed;
1866  }
1867
1868  static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
1869    checkNotNull(collection); // for GWT
1870    if (collection instanceof Multiset) {
1871      collection = ((Multiset<?>) collection).elementSet();
1872    }
1873    /*
1874     * AbstractSet.removeAll(List) has quadratic behavior if the list size
1875     * is just less than the set's size.  We augment the test by
1876     * assuming that sets have fast contains() performance, and other
1877     * collections don't.  See
1878     * http://code.google.com/p/guava-libraries/issues/detail?id=1013
1879     */
1880    if (collection instanceof Set && collection.size() > set.size()) {
1881      return Iterators.removeAll(set.iterator(), collection);
1882    } else {
1883      return removeAllImpl(set, collection.iterator());
1884    }
1885  }
1886
1887  @GwtIncompatible // NavigableSet
1888  static class DescendingSet<E> extends ForwardingNavigableSet<E> {
1889    private final NavigableSet<E> forward;
1890
1891    DescendingSet(NavigableSet<E> forward) {
1892      this.forward = forward;
1893    }
1894
1895    @Override
1896    protected NavigableSet<E> delegate() {
1897      return forward;
1898    }
1899
1900    @Override
1901    public E lower(E e) {
1902      return forward.higher(e);
1903    }
1904
1905    @Override
1906    public E floor(E e) {
1907      return forward.ceiling(e);
1908    }
1909
1910    @Override
1911    public E ceiling(E e) {
1912      return forward.floor(e);
1913    }
1914
1915    @Override
1916    public E higher(E e) {
1917      return forward.lower(e);
1918    }
1919
1920    @Override
1921    public E pollFirst() {
1922      return forward.pollLast();
1923    }
1924
1925    @Override
1926    public E pollLast() {
1927      return forward.pollFirst();
1928    }
1929
1930    @Override
1931    public NavigableSet<E> descendingSet() {
1932      return forward;
1933    }
1934
1935    @Override
1936    public Iterator<E> descendingIterator() {
1937      return forward.iterator();
1938    }
1939
1940    @Override
1941    public NavigableSet<E> subSet(
1942        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
1943      return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
1944    }
1945
1946    @Override
1947    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1948      return forward.tailSet(toElement, inclusive).descendingSet();
1949    }
1950
1951    @Override
1952    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1953      return forward.headSet(fromElement, inclusive).descendingSet();
1954    }
1955
1956    @SuppressWarnings("unchecked")
1957    @Override
1958    public Comparator<? super E> comparator() {
1959      Comparator<? super E> forwardComparator = forward.comparator();
1960      if (forwardComparator == null) {
1961        return (Comparator) Ordering.natural().reverse();
1962      } else {
1963        return reverse(forwardComparator);
1964      }
1965    }
1966
1967    // If we inline this, we get a javac error.
1968    private static <T> Ordering<T> reverse(Comparator<T> forward) {
1969      return Ordering.from(forward).reverse();
1970    }
1971
1972    @Override
1973    public E first() {
1974      return forward.last();
1975    }
1976
1977    @Override
1978    public SortedSet<E> headSet(E toElement) {
1979      return standardHeadSet(toElement);
1980    }
1981
1982    @Override
1983    public E last() {
1984      return forward.first();
1985    }
1986
1987    @Override
1988    public SortedSet<E> subSet(E fromElement, E toElement) {
1989      return standardSubSet(fromElement, toElement);
1990    }
1991
1992    @Override
1993    public SortedSet<E> tailSet(E fromElement) {
1994      return standardTailSet(fromElement);
1995    }
1996
1997    @Override
1998    public Iterator<E> iterator() {
1999      return forward.descendingIterator();
2000    }
2001
2002    @Override
2003    public Object[] toArray() {
2004      return standardToArray();
2005    }
2006
2007    @Override
2008    public <T> T[] toArray(T[] array) {
2009      return standardToArray(array);
2010    }
2011
2012    @Override
2013    public String toString() {
2014      return standardToString();
2015    }
2016  }
2017
2018  /**
2019   * Returns a view of the portion of {@code set} whose elements are contained by {@code range}.
2020   *
2021   * <p>This method delegates to the appropriate methods of {@link NavigableSet} (namely
2022   * {@link NavigableSet#subSet(Object, boolean, Object, boolean) subSet()},
2023   * {@link NavigableSet#tailSet(Object, boolean) tailSet()}, and
2024   * {@link NavigableSet#headSet(Object, boolean) headSet()}) to actually construct the view.
2025   * Consult these methods for a full description of the returned view's behavior.
2026   *
2027   * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
2028   * ordering. {@code NavigableSet} on the other hand can specify a custom ordering via a
2029   * {@link Comparator}, which can violate the natural ordering. Using this method (or in general
2030   * using {@code Range}) with unnaturally-ordered sets can lead to unexpected and undefined
2031   * behavior.
2032   *
2033   * @since 20.0
2034   */
2035  @Beta
2036  @GwtIncompatible // NavigableSet
2037  public static <K extends Comparable<? super K>> NavigableSet<K> subSet(
2038      NavigableSet<K> set, Range<K> range) {
2039    if (set.comparator() != null
2040        && set.comparator() != Ordering.natural()
2041        && range.hasLowerBound()
2042        && range.hasUpperBound()) {
2043      checkArgument(
2044          set.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
2045          "set is using a custom comparator which is inconsistent with the natural ordering.");
2046    }
2047    if (range.hasLowerBound() && range.hasUpperBound()) {
2048      return set.subSet(
2049          range.lowerEndpoint(),
2050          range.lowerBoundType() == BoundType.CLOSED,
2051          range.upperEndpoint(),
2052          range.upperBoundType() == BoundType.CLOSED);
2053    } else if (range.hasLowerBound()) {
2054      return set.tailSet(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
2055    } else if (range.hasUpperBound()) {
2056      return set.headSet(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
2057    }
2058    return checkNotNull(set);
2059  }
2060}