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