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