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