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