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