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            // redeclare to help optimizers with b/310253115
1437            @SuppressWarnings("RedundantOverride")
1438            @Override
1439            @J2ktIncompatible // serialization
1440            @GwtIncompatible // serialization
1441            Object writeReplace() {
1442              return super.writeReplace();
1443            }
1444          };
1445      return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
1446    }
1447
1448    private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
1449      this.axes = axes;
1450      this.delegate = delegate;
1451    }
1452
1453    @Override
1454    protected Collection<List<E>> delegate() {
1455      return delegate;
1456    }
1457
1458    @Override
1459    public boolean contains(@CheckForNull Object object) {
1460      if (!(object instanceof List)) {
1461        return false;
1462      }
1463      List<?> list = (List<?>) object;
1464      if (list.size() != axes.size()) {
1465        return false;
1466      }
1467      int i = 0;
1468      for (Object o : list) {
1469        if (!axes.get(i).contains(o)) {
1470          return false;
1471        }
1472        i++;
1473      }
1474      return true;
1475    }
1476
1477    @Override
1478    public boolean equals(@CheckForNull Object object) {
1479      // Warning: this is broken if size() == 0, so it is critical that we
1480      // substitute an empty ImmutableSet to the user in place of this
1481      if (object instanceof CartesianSet) {
1482        CartesianSet<?> that = (CartesianSet<?>) object;
1483        return this.axes.equals(that.axes);
1484      }
1485      if (object instanceof Set) {
1486        Set<?> that = (Set<?>) object;
1487        return this.size() == that.size() && this.containsAll(that);
1488      }
1489      return false;
1490    }
1491
1492    @Override
1493    public int hashCode() {
1494      // Warning: this is broken if size() == 0, so it is critical that we
1495      // substitute an empty ImmutableSet to the user in place of this
1496
1497      // It's a weird formula, but tests prove it works.
1498      int adjust = size() - 1;
1499      for (int i = 0; i < axes.size(); i++) {
1500        adjust *= 31;
1501        adjust = ~~adjust;
1502        // in GWT, we have to deal with integer overflow carefully
1503      }
1504      int hash = 1;
1505      for (Set<E> axis : axes) {
1506        hash = 31 * hash + (size() / axis.size() * axis.hashCode());
1507
1508        hash = ~~hash;
1509      }
1510      hash += adjust;
1511      return ~~hash;
1512    }
1513  }
1514
1515  /**
1516   * Returns the set of all possible subsets of {@code set}. For example, {@code
1517   * powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, {1}, {2}, {1, 2}}}.
1518   *
1519   * <p>Elements appear in these subsets in the same iteration order as they appeared in the input
1520   * set. The order in which these subsets appear in the outer set is undefined. Note that the power
1521   * set of the empty set is not the empty set, but a one-element set containing the empty set.
1522   *
1523   * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements
1524   * are identical, even if the input set uses a different concept of equivalence.
1525   *
1526   * <p><i>Performance notes:</i> while the power set of a set with size {@code n} is of size {@code
1527   * 2^n}, its memory usage is only {@code O(n)}. When the power set is constructed, the input set
1528   * is merely copied. Only as the power set is iterated are the individual subsets created, and
1529   * these subsets themselves occupy only a small constant amount of memory.
1530   *
1531   * @param set the set of elements to construct a power set from
1532   * @return the power set, as an immutable set of immutable sets
1533   * @throws IllegalArgumentException if {@code set} has more than 30 unique elements (causing the
1534   *     power set size to exceed the {@code int} range)
1535   * @throws NullPointerException if {@code set} is or contains {@code null}
1536   * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at Wikipedia</a>
1537   * @since 4.0
1538   */
1539  @GwtCompatible(serializable = false)
1540  public static <E> Set<Set<E>> powerSet(Set<E> set) {
1541    return new PowerSet<E>(set);
1542  }
1543
1544  private static final class SubSet<E> extends AbstractSet<E> {
1545    private final ImmutableMap<E, Integer> inputSet;
1546    private final int mask;
1547
1548    SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
1549      this.inputSet = inputSet;
1550      this.mask = mask;
1551    }
1552
1553    @Override
1554    public Iterator<E> iterator() {
1555      return new UnmodifiableIterator<E>() {
1556        final ImmutableList<E> elements = inputSet.keySet().asList();
1557        int remainingSetBits = mask;
1558
1559        @Override
1560        public boolean hasNext() {
1561          return remainingSetBits != 0;
1562        }
1563
1564        @Override
1565        public E next() {
1566          int index = Integer.numberOfTrailingZeros(remainingSetBits);
1567          if (index == 32) {
1568            throw new NoSuchElementException();
1569          }
1570          remainingSetBits &= ~(1 << index);
1571          return elements.get(index);
1572        }
1573      };
1574    }
1575
1576    @Override
1577    public int size() {
1578      return Integer.bitCount(mask);
1579    }
1580
1581    @Override
1582    public boolean contains(@CheckForNull Object o) {
1583      Integer index = inputSet.get(o);
1584      return index != null && (mask & (1 << index)) != 0;
1585    }
1586  }
1587
1588  private static final class PowerSet<E> extends AbstractSet<Set<E>> {
1589    final ImmutableMap<E, Integer> inputSet;
1590
1591    PowerSet(Set<E> input) {
1592      checkArgument(
1593          input.size() <= 30, "Too many elements to create power set: %s > 30", input.size());
1594      this.inputSet = Maps.indexMap(input);
1595    }
1596
1597    @Override
1598    public int size() {
1599      return 1 << inputSet.size();
1600    }
1601
1602    @Override
1603    public boolean isEmpty() {
1604      return false;
1605    }
1606
1607    @Override
1608    public Iterator<Set<E>> iterator() {
1609      return new AbstractIndexedListIterator<Set<E>>(size()) {
1610        @Override
1611        protected Set<E> get(final int setBits) {
1612          return new SubSet<E>(inputSet, setBits);
1613        }
1614      };
1615    }
1616
1617    @Override
1618    public boolean contains(@CheckForNull Object obj) {
1619      if (obj instanceof Set) {
1620        Set<?> set = (Set<?>) obj;
1621        return inputSet.keySet().containsAll(set);
1622      }
1623      return false;
1624    }
1625
1626    @Override
1627    public boolean equals(@CheckForNull Object obj) {
1628      if (obj instanceof PowerSet) {
1629        PowerSet<?> that = (PowerSet<?>) obj;
1630        return inputSet.keySet().equals(that.inputSet.keySet());
1631      }
1632      return super.equals(obj);
1633    }
1634
1635    @Override
1636    public int hashCode() {
1637      /*
1638       * The sum of the sums of the hash codes in each subset is just the sum of
1639       * each input element's hash code times the number of sets that element
1640       * appears in. Each element appears in exactly half of the 2^n sets, so:
1641       */
1642      return inputSet.keySet().hashCode() << (inputSet.size() - 1);
1643    }
1644
1645    @Override
1646    public String toString() {
1647      return "powerSet(" + inputSet + ")";
1648    }
1649  }
1650
1651  /**
1652   * Returns the set of all subsets of {@code set} of size {@code size}. For example, {@code
1653   * combinations(ImmutableSet.of(1, 2, 3), 2)} returns the set {@code {{1, 2}, {1, 3}, {2, 3}}}.
1654   *
1655   * <p>Elements appear in these subsets in the same iteration order as they appeared in the input
1656   * set. The order in which these subsets appear in the outer set is undefined.
1657   *
1658   * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements
1659   * are identical, even if the input set uses a different concept of equivalence.
1660   *
1661   * <p><i>Performance notes:</i> the memory usage of the returned set is only {@code O(n)}. When
1662   * the result set is constructed, the input set is merely copied. Only as the result set is
1663   * iterated are the individual subsets created. Each of these subsets occupies an additional O(n)
1664   * memory but only for as long as the user retains a reference to it. That is, the set returned by
1665   * {@code combinations} does not retain the individual subsets.
1666   *
1667   * @param set the set of elements to take combinations of
1668   * @param size the number of elements per combination
1669   * @return the set of all combinations of {@code size} elements from {@code set}
1670   * @throws IllegalArgumentException if {@code size} is not between 0 and {@code set.size()}
1671   *     inclusive
1672   * @throws NullPointerException if {@code set} is or contains {@code null}
1673   * @since 23.0
1674   */
1675  public static <E> Set<Set<E>> combinations(Set<E> set, final int size) {
1676    final ImmutableMap<E, Integer> index = Maps.indexMap(set);
1677    checkNonnegative(size, "size");
1678    checkArgument(size <= index.size(), "size (%s) must be <= set.size() (%s)", size, index.size());
1679    if (size == 0) {
1680      return ImmutableSet.<Set<E>>of(ImmutableSet.<E>of());
1681    } else if (size == index.size()) {
1682      return ImmutableSet.<Set<E>>of(index.keySet());
1683    }
1684    return new AbstractSet<Set<E>>() {
1685      @Override
1686      public boolean contains(@CheckForNull Object o) {
1687        if (o instanceof Set) {
1688          Set<?> s = (Set<?>) o;
1689          return s.size() == size && index.keySet().containsAll(s);
1690        }
1691        return false;
1692      }
1693
1694      @Override
1695      public Iterator<Set<E>> iterator() {
1696        return new AbstractIterator<Set<E>>() {
1697          final BitSet bits = new BitSet(index.size());
1698
1699          @Override
1700          @CheckForNull
1701          protected Set<E> computeNext() {
1702            if (bits.isEmpty()) {
1703              bits.set(0, size);
1704            } else {
1705              int firstSetBit = bits.nextSetBit(0);
1706              int bitToFlip = bits.nextClearBit(firstSetBit);
1707
1708              if (bitToFlip == index.size()) {
1709                return endOfData();
1710              }
1711
1712              /*
1713               * The current set in sorted order looks like
1714               * {firstSetBit, firstSetBit + 1, ..., bitToFlip - 1, ...}
1715               * where it does *not* contain bitToFlip.
1716               *
1717               * The next combination is
1718               *
1719               * {0, 1, ..., bitToFlip - firstSetBit - 2, bitToFlip, ...}
1720               *
1721               * This is lexicographically next if you look at the combinations in descending order
1722               * e.g. {2, 1, 0}, {3, 1, 0}, {3, 2, 0}, {3, 2, 1}, {4, 1, 0}...
1723               */
1724
1725              bits.set(0, bitToFlip - firstSetBit - 1);
1726              bits.clear(bitToFlip - firstSetBit - 1, bitToFlip);
1727              bits.set(bitToFlip);
1728            }
1729            final BitSet copy = (BitSet) bits.clone();
1730            return new AbstractSet<E>() {
1731              @Override
1732              public boolean contains(@CheckForNull Object o) {
1733                Integer i = index.get(o);
1734                return i != null && copy.get(i);
1735              }
1736
1737              @Override
1738              public Iterator<E> iterator() {
1739                return new AbstractIterator<E>() {
1740                  int i = -1;
1741
1742                  @Override
1743                  @CheckForNull
1744                  protected E computeNext() {
1745                    i = copy.nextSetBit(i + 1);
1746                    if (i == -1) {
1747                      return endOfData();
1748                    }
1749                    return index.keySet().asList().get(i);
1750                  }
1751                };
1752              }
1753
1754              @Override
1755              public int size() {
1756                return size;
1757              }
1758            };
1759          }
1760        };
1761      }
1762
1763      @Override
1764      public int size() {
1765        return IntMath.binomial(index.size(), size);
1766      }
1767
1768      @Override
1769      public String toString() {
1770        return "Sets.combinations(" + index.keySet() + ", " + size + ")";
1771      }
1772    };
1773  }
1774
1775  /** An implementation for {@link Set#hashCode()}. */
1776  static int hashCodeImpl(Set<?> s) {
1777    int hashCode = 0;
1778    for (Object o : s) {
1779      hashCode += o != null ? o.hashCode() : 0;
1780
1781      hashCode = ~~hashCode;
1782      // Needed to deal with unusual integer overflow in GWT.
1783    }
1784    return hashCode;
1785  }
1786
1787  /** An implementation for {@link Set#equals(Object)}. */
1788  static boolean equalsImpl(Set<?> s, @CheckForNull Object object) {
1789    if (s == object) {
1790      return true;
1791    }
1792    if (object instanceof Set) {
1793      Set<?> o = (Set<?>) object;
1794
1795      try {
1796        return s.size() == o.size() && s.containsAll(o);
1797      } catch (NullPointerException | ClassCastException ignored) {
1798        return false;
1799      }
1800    }
1801    return false;
1802  }
1803
1804  /**
1805   * Returns an unmodifiable view of the specified navigable set. This method allows modules to
1806   * provide users with "read-only" access to internal navigable sets. Query operations on the
1807   * returned set "read through" to the specified set, and attempts to modify the returned set,
1808   * whether direct or via its collection views, result in an {@code UnsupportedOperationException}.
1809   *
1810   * <p>The returned navigable set will be serializable if the specified navigable set is
1811   * serializable.
1812   *
1813   * <p><b>Java 8 users and later:</b> Prefer {@link Collections#unmodifiableNavigableSet}.
1814   *
1815   * @param set the navigable set for which an unmodifiable view is to be returned
1816   * @return an unmodifiable view of the specified navigable set
1817   * @since 12.0
1818   */
1819  public static <E extends @Nullable Object> NavigableSet<E> unmodifiableNavigableSet(
1820      NavigableSet<E> set) {
1821    if (set instanceof ImmutableCollection || set instanceof UnmodifiableNavigableSet) {
1822      return set;
1823    }
1824    return new UnmodifiableNavigableSet<E>(set);
1825  }
1826
1827  static final class UnmodifiableNavigableSet<E extends @Nullable Object>
1828      extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable {
1829    private final NavigableSet<E> delegate;
1830    private final SortedSet<E> unmodifiableDelegate;
1831
1832    UnmodifiableNavigableSet(NavigableSet<E> delegate) {
1833      this.delegate = checkNotNull(delegate);
1834      this.unmodifiableDelegate = Collections.unmodifiableSortedSet(delegate);
1835    }
1836
1837    @Override
1838    protected SortedSet<E> delegate() {
1839      return unmodifiableDelegate;
1840    }
1841
1842    // default methods not forwarded by ForwardingSortedSet
1843
1844    @Override
1845    public boolean removeIf(java.util.function.Predicate<? super E> filter) {
1846      throw new UnsupportedOperationException();
1847    }
1848
1849    @Override
1850    public Stream<E> stream() {
1851      return delegate.stream();
1852    }
1853
1854    @Override
1855    public Stream<E> parallelStream() {
1856      return delegate.parallelStream();
1857    }
1858
1859    @Override
1860    public void forEach(Consumer<? super E> action) {
1861      delegate.forEach(action);
1862    }
1863
1864    @Override
1865    @CheckForNull
1866    public E lower(@ParametricNullness E e) {
1867      return delegate.lower(e);
1868    }
1869
1870    @Override
1871    @CheckForNull
1872    public E floor(@ParametricNullness E e) {
1873      return delegate.floor(e);
1874    }
1875
1876    @Override
1877    @CheckForNull
1878    public E ceiling(@ParametricNullness E e) {
1879      return delegate.ceiling(e);
1880    }
1881
1882    @Override
1883    @CheckForNull
1884    public E higher(@ParametricNullness E e) {
1885      return delegate.higher(e);
1886    }
1887
1888    @Override
1889    @CheckForNull
1890    public E pollFirst() {
1891      throw new UnsupportedOperationException();
1892    }
1893
1894    @Override
1895    @CheckForNull
1896    public E pollLast() {
1897      throw new UnsupportedOperationException();
1898    }
1899
1900    @LazyInit @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet;
1901
1902    @Override
1903    public NavigableSet<E> descendingSet() {
1904      UnmodifiableNavigableSet<E> result = descendingSet;
1905      if (result == null) {
1906        result = descendingSet = new UnmodifiableNavigableSet<E>(delegate.descendingSet());
1907        result.descendingSet = this;
1908      }
1909      return result;
1910    }
1911
1912    @Override
1913    public Iterator<E> descendingIterator() {
1914      return Iterators.unmodifiableIterator(delegate.descendingIterator());
1915    }
1916
1917    @Override
1918    public NavigableSet<E> subSet(
1919        @ParametricNullness E fromElement,
1920        boolean fromInclusive,
1921        @ParametricNullness E toElement,
1922        boolean toInclusive) {
1923      return unmodifiableNavigableSet(
1924          delegate.subSet(fromElement, fromInclusive, toElement, toInclusive));
1925    }
1926
1927    @Override
1928    public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
1929      return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive));
1930    }
1931
1932    @Override
1933    public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
1934      return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive));
1935    }
1936
1937    private static final long serialVersionUID = 0;
1938  }
1939
1940  /**
1941   * Returns a synchronized (thread-safe) navigable set backed by the specified navigable set. In
1942   * order to guarantee serial access, it is critical that <b>all</b> access to the backing
1943   * navigable set is accomplished through the returned navigable set (or its views).
1944   *
1945   * <p>It is imperative that the user manually synchronize on the returned sorted set when
1946   * iterating over it or any of its {@code descendingSet}, {@code subSet}, {@code headSet}, or
1947   * {@code tailSet} views.
1948   *
1949   * <pre>{@code
1950   * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
1951   *  ...
1952   * synchronized (set) {
1953   *   // Must be in the synchronized block
1954   *   Iterator<E> it = set.iterator();
1955   *   while (it.hasNext()) {
1956   *     foo(it.next());
1957   *   }
1958   * }
1959   * }</pre>
1960   *
1961   * <p>or:
1962   *
1963   * <pre>{@code
1964   * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
1965   * NavigableSet<E> set2 = set.descendingSet().headSet(foo);
1966   *  ...
1967   * synchronized (set) { // Note: set, not set2!!!
1968   *   // Must be in the synchronized block
1969   *   Iterator<E> it = set2.descendingIterator();
1970   *   while (it.hasNext())
1971   *     foo(it.next());
1972   *   }
1973   * }
1974   * }</pre>
1975   *
1976   * <p>Failure to follow this advice may result in non-deterministic behavior.
1977   *
1978   * <p>The returned navigable set will be serializable if the specified navigable set is
1979   * serializable.
1980   *
1981   * <p><b>Java 8 users and later:</b> Prefer {@link Collections#synchronizedNavigableSet}.
1982   *
1983   * @param navigableSet the navigable set to be "wrapped" in a synchronized navigable set.
1984   * @return a synchronized view of the specified navigable set.
1985   * @since 13.0
1986   */
1987  @GwtIncompatible // NavigableSet
1988  public static <E extends @Nullable Object> NavigableSet<E> synchronizedNavigableSet(
1989      NavigableSet<E> navigableSet) {
1990    return Synchronized.navigableSet(navigableSet);
1991  }
1992
1993  /** Remove each element in an iterable from a set. */
1994  static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
1995    boolean changed = false;
1996    while (iterator.hasNext()) {
1997      changed |= set.remove(iterator.next());
1998    }
1999    return changed;
2000  }
2001
2002  static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
2003    checkNotNull(collection); // for GWT
2004    if (collection instanceof Multiset) {
2005      collection = ((Multiset<?>) collection).elementSet();
2006    }
2007    /*
2008     * AbstractSet.removeAll(List) has quadratic behavior if the list size
2009     * is just more than the set's size.  We augment the test by
2010     * assuming that sets have fast contains() performance, and other
2011     * collections don't.  See
2012     * http://code.google.com/p/guava-libraries/issues/detail?id=1013
2013     */
2014    if (collection instanceof Set && collection.size() > set.size()) {
2015      return Iterators.removeAll(set.iterator(), collection);
2016    } else {
2017      return removeAllImpl(set, collection.iterator());
2018    }
2019  }
2020
2021  @GwtIncompatible // NavigableSet
2022  static class DescendingSet<E extends @Nullable Object> extends ForwardingNavigableSet<E> {
2023    private final NavigableSet<E> forward;
2024
2025    DescendingSet(NavigableSet<E> forward) {
2026      this.forward = forward;
2027    }
2028
2029    @Override
2030    protected NavigableSet<E> delegate() {
2031      return forward;
2032    }
2033
2034    @Override
2035    @CheckForNull
2036    public E lower(@ParametricNullness E e) {
2037      return forward.higher(e);
2038    }
2039
2040    @Override
2041    @CheckForNull
2042    public E floor(@ParametricNullness E e) {
2043      return forward.ceiling(e);
2044    }
2045
2046    @Override
2047    @CheckForNull
2048    public E ceiling(@ParametricNullness E e) {
2049      return forward.floor(e);
2050    }
2051
2052    @Override
2053    @CheckForNull
2054    public E higher(@ParametricNullness E e) {
2055      return forward.lower(e);
2056    }
2057
2058    @Override
2059    @CheckForNull
2060    public E pollFirst() {
2061      return forward.pollLast();
2062    }
2063
2064    @Override
2065    @CheckForNull
2066    public E pollLast() {
2067      return forward.pollFirst();
2068    }
2069
2070    @Override
2071    public NavigableSet<E> descendingSet() {
2072      return forward;
2073    }
2074
2075    @Override
2076    public Iterator<E> descendingIterator() {
2077      return forward.iterator();
2078    }
2079
2080    @Override
2081    public NavigableSet<E> subSet(
2082        @ParametricNullness E fromElement,
2083        boolean fromInclusive,
2084        @ParametricNullness E toElement,
2085        boolean toInclusive) {
2086      return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
2087    }
2088
2089    @Override
2090    public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) {
2091      return standardSubSet(fromElement, toElement);
2092    }
2093
2094    @Override
2095    public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
2096      return forward.tailSet(toElement, inclusive).descendingSet();
2097    }
2098
2099    @Override
2100    public SortedSet<E> headSet(@ParametricNullness E toElement) {
2101      return standardHeadSet(toElement);
2102    }
2103
2104    @Override
2105    public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
2106      return forward.headSet(fromElement, inclusive).descendingSet();
2107    }
2108
2109    @Override
2110    public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
2111      return standardTailSet(fromElement);
2112    }
2113
2114    @SuppressWarnings("unchecked")
2115    @Override
2116    public Comparator<? super E> comparator() {
2117      Comparator<? super E> forwardComparator = forward.comparator();
2118      if (forwardComparator == null) {
2119        return (Comparator) Ordering.natural().reverse();
2120      } else {
2121        return reverse(forwardComparator);
2122      }
2123    }
2124
2125    // If we inline this, we get a javac error.
2126    private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) {
2127      return Ordering.from(forward).reverse();
2128    }
2129
2130    @Override
2131    @ParametricNullness
2132    public E first() {
2133      return forward.last();
2134    }
2135
2136    @Override
2137    @ParametricNullness
2138    public E last() {
2139      return forward.first();
2140    }
2141
2142    @Override
2143    public Iterator<E> iterator() {
2144      return forward.descendingIterator();
2145    }
2146
2147    @Override
2148    public @Nullable Object[] toArray() {
2149      return standardToArray();
2150    }
2151
2152    @Override
2153    @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
2154    public <T extends @Nullable Object> T[] toArray(T[] array) {
2155      return standardToArray(array);
2156    }
2157
2158    @Override
2159    public String toString() {
2160      return standardToString();
2161    }
2162  }
2163
2164  /**
2165   * Returns a view of the portion of {@code set} whose elements are contained by {@code range}.
2166   *
2167   * <p>This method delegates to the appropriate methods of {@link NavigableSet} (namely {@link
2168   * NavigableSet#subSet(Object, boolean, Object, boolean) subSet()}, {@link
2169   * NavigableSet#tailSet(Object, boolean) tailSet()}, and {@link NavigableSet#headSet(Object,
2170   * boolean) headSet()}) to actually construct the view. Consult these methods for a full
2171   * description of the returned view's behavior.
2172   *
2173   * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
2174   * ordering. {@code NavigableSet} on the other hand can specify a custom ordering via a {@link
2175   * Comparator}, which can violate the natural ordering. Using this method (or in general using
2176   * {@code Range}) with unnaturally-ordered sets can lead to unexpected and undefined behavior.
2177   *
2178   * @since 20.0
2179   */
2180  @GwtIncompatible // NavigableSet
2181  public static <K extends Comparable<? super K>> NavigableSet<K> subSet(
2182      NavigableSet<K> set, Range<K> range) {
2183    if (set.comparator() != null
2184        && set.comparator() != Ordering.natural()
2185        && range.hasLowerBound()
2186        && range.hasUpperBound()) {
2187      checkArgument(
2188          set.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
2189          "set is using a custom comparator which is inconsistent with the natural ordering.");
2190    }
2191    if (range.hasLowerBound() && range.hasUpperBound()) {
2192      return set.subSet(
2193          range.lowerEndpoint(),
2194          range.lowerBoundType() == BoundType.CLOSED,
2195          range.upperEndpoint(),
2196          range.upperBoundType() == BoundType.CLOSED);
2197    } else if (range.hasLowerBound()) {
2198      return set.tailSet(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
2199    } else if (range.hasUpperBound()) {
2200      return set.headSet(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
2201    }
2202    return checkNotNull(set);
2203  }
2204}