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