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