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