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