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