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