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