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