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