001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.collect; 018 019import static com.google.common.base.Preconditions.checkArgument; 020import static com.google.common.base.Preconditions.checkNotNull; 021import static com.google.common.collect.CollectPreconditions.checkNonnegative; 022 023import com.google.common.annotations.GwtCompatible; 024import com.google.common.annotations.GwtIncompatible; 025import com.google.common.annotations.J2ktIncompatible; 026import com.google.common.base.Predicate; 027import com.google.common.base.Predicates; 028import com.google.common.collect.Collections2.FilteredCollection; 029import com.google.common.math.IntMath; 030import com.google.errorprone.annotations.CanIgnoreReturnValue; 031import com.google.errorprone.annotations.DoNotCall; 032import com.google.errorprone.annotations.concurrent.LazyInit; 033import java.io.Serializable; 034import java.util.AbstractSet; 035import java.util.Arrays; 036import java.util.BitSet; 037import java.util.Collection; 038import java.util.Collections; 039import java.util.Comparator; 040import java.util.EnumSet; 041import java.util.HashSet; 042import java.util.Iterator; 043import java.util.LinkedHashSet; 044import java.util.List; 045import java.util.Map; 046import java.util.NavigableSet; 047import java.util.NoSuchElementException; 048import java.util.Set; 049import java.util.SortedSet; 050import java.util.TreeSet; 051import java.util.concurrent.ConcurrentHashMap; 052import java.util.concurrent.CopyOnWriteArraySet; 053import java.util.function.Consumer; 054import java.util.stream.Collector; 055import java.util.stream.Stream; 056import javax.annotation.CheckForNull; 057import org.checkerframework.checker.nullness.qual.NonNull; 058import org.checkerframework.checker.nullness.qual.Nullable; 059 060/** 061 * Static utility methods pertaining to {@link Set} instances. Also see this class's counterparts 062 * {@link Lists}, {@link Maps} and {@link Queues}. 063 * 064 * <p>See the Guava User Guide article on <a href= 065 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#sets">{@code Sets}</a>. 066 * 067 * @author Kevin Bourrillion 068 * @author Jared Levy 069 * @author Chris Povirk 070 * @since 2.0 071 */ 072@GwtCompatible(emulated = true) 073@ElementTypesAreNonnullByDefault 074public final class Sets { 075 private Sets() {} 076 077 /** 078 * {@link AbstractSet} substitute without the potentially-quadratic {@code removeAll} 079 * implementation. 080 */ 081 abstract static class ImprovedAbstractSet<E extends @Nullable Object> extends AbstractSet<E> { 082 @Override 083 public boolean removeAll(Collection<?> c) { 084 return removeAllImpl(this, c); 085 } 086 087 @Override 088 public boolean retainAll(Collection<?> c) { 089 return super.retainAll(checkNotNull(c)); // GWT compatibility 090 } 091 } 092 093 /** 094 * Returns an immutable set instance containing the given enum elements. Internally, the returned 095 * set will be backed by an {@link EnumSet}. 096 * 097 * <p>The iteration order of the returned set follows the enum's iteration order, not the order in 098 * which the elements are provided to the method. 099 * 100 * @param anElement one of the elements the set should contain 101 * @param otherElements the rest of the elements the set should contain 102 * @return an immutable set containing those elements, minus duplicates 103 */ 104 // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 105 @GwtCompatible(serializable = true) 106 public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet( 107 E anElement, E... otherElements) { 108 return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements)); 109 } 110 111 /** 112 * Returns an immutable set instance containing the given enum elements. Internally, the returned 113 * set will be backed by an {@link EnumSet}. 114 * 115 * <p>The iteration order of the returned set follows the enum's iteration order, not the order in 116 * which the elements appear in the given collection. 117 * 118 * @param elements the elements, all of the same {@code enum} type, that the set should contain 119 * @return an immutable set containing those elements, minus duplicates 120 */ 121 // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 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 @SuppressWarnings("nullness") // Unsafe, but we can't fix it now. 604 public ImmutableSet<@NonNull E> immutableCopy() { 605 return ImmutableSet.copyOf((SetView<@NonNull E>) this); 606 } 607 608 /** 609 * Copies the current contents of this set view into an existing set. This method has equivalent 610 * behavior to {@code set.addAll(this)}, assuming that all the sets involved are based on the 611 * same notion of equivalence. 612 * 613 * @return a reference to {@code set}, for convenience 614 */ 615 // Note: S should logically extend Set<? super E> but can't due to either 616 // some javac bug or some weirdness in the spec, not sure which. 617 @CanIgnoreReturnValue 618 public <S extends Set<E>> S copyInto(S set) { 619 set.addAll(this); 620 return set; 621 } 622 623 /** 624 * Guaranteed to throw an exception and leave the collection unmodified. 625 * 626 * @throws UnsupportedOperationException always 627 * @deprecated Unsupported operation. 628 */ 629 @CanIgnoreReturnValue 630 @Deprecated 631 @Override 632 @DoNotCall("Always throws UnsupportedOperationException") 633 public final boolean add(@ParametricNullness E e) { 634 throw new UnsupportedOperationException(); 635 } 636 637 /** 638 * Guaranteed to throw an exception and leave the collection unmodified. 639 * 640 * @throws UnsupportedOperationException always 641 * @deprecated Unsupported operation. 642 */ 643 @CanIgnoreReturnValue 644 @Deprecated 645 @Override 646 @DoNotCall("Always throws UnsupportedOperationException") 647 public final boolean remove(@CheckForNull Object object) { 648 throw new UnsupportedOperationException(); 649 } 650 651 /** 652 * Guaranteed to throw an exception and leave the collection unmodified. 653 * 654 * @throws UnsupportedOperationException always 655 * @deprecated Unsupported operation. 656 */ 657 @CanIgnoreReturnValue 658 @Deprecated 659 @Override 660 @DoNotCall("Always throws UnsupportedOperationException") 661 public final boolean addAll(Collection<? extends E> newElements) { 662 throw new UnsupportedOperationException(); 663 } 664 665 /** 666 * Guaranteed to throw an exception and leave the collection unmodified. 667 * 668 * @throws UnsupportedOperationException always 669 * @deprecated Unsupported operation. 670 */ 671 @CanIgnoreReturnValue 672 @Deprecated 673 @Override 674 @DoNotCall("Always throws UnsupportedOperationException") 675 public final boolean removeAll(Collection<?> oldElements) { 676 throw new UnsupportedOperationException(); 677 } 678 679 /** 680 * Guaranteed to throw an exception and leave the collection unmodified. 681 * 682 * @throws UnsupportedOperationException always 683 * @deprecated Unsupported operation. 684 */ 685 @CanIgnoreReturnValue 686 @Deprecated 687 @Override 688 @DoNotCall("Always throws UnsupportedOperationException") 689 public final boolean removeIf(java.util.function.Predicate<? super E> filter) { 690 throw new UnsupportedOperationException(); 691 } 692 693 /** 694 * Guaranteed to throw an exception and leave the collection unmodified. 695 * 696 * @throws UnsupportedOperationException always 697 * @deprecated Unsupported operation. 698 */ 699 @CanIgnoreReturnValue 700 @Deprecated 701 @Override 702 @DoNotCall("Always throws UnsupportedOperationException") 703 public final boolean retainAll(Collection<?> elementsToKeep) { 704 throw new UnsupportedOperationException(); 705 } 706 707 /** 708 * Guaranteed to throw an exception and leave the collection unmodified. 709 * 710 * @throws UnsupportedOperationException always 711 * @deprecated Unsupported operation. 712 */ 713 @Deprecated 714 @Override 715 @DoNotCall("Always throws UnsupportedOperationException") 716 public final void clear() { 717 throw new UnsupportedOperationException(); 718 } 719 720 /** 721 * Scope the return type to {@link UnmodifiableIterator} to ensure this is an unmodifiable view. 722 * 723 * @since 20.0 (present with return type {@link Iterator} since 2.0) 724 */ 725 @Override 726 public abstract UnmodifiableIterator<E> iterator(); 727 } 728 729 /** 730 * Returns an unmodifiable <b>view</b> of the union of two sets. The returned set contains all 731 * elements that are contained in either backing set. Iterating over the returned set iterates 732 * first over all the elements of {@code set1}, then over each element of {@code set2}, in order, 733 * that is not contained in {@code set1}. 734 * 735 * <p>Results are undefined if {@code set1} and {@code set2} are sets based on different 736 * equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a 737 * {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}. 738 */ 739 public static <E extends @Nullable Object> SetView<E> union( 740 final Set<? extends E> set1, final Set<? extends E> set2) { 741 checkNotNull(set1, "set1"); 742 checkNotNull(set2, "set2"); 743 744 return new SetView<E>() { 745 @Override 746 public int size() { 747 int size = set1.size(); 748 for (E e : set2) { 749 if (!set1.contains(e)) { 750 size++; 751 } 752 } 753 return size; 754 } 755 756 @Override 757 public boolean isEmpty() { 758 return set1.isEmpty() && set2.isEmpty(); 759 } 760 761 @Override 762 public UnmodifiableIterator<E> iterator() { 763 return new AbstractIterator<E>() { 764 final Iterator<? extends E> itr1 = set1.iterator(); 765 final Iterator<? extends E> itr2 = set2.iterator(); 766 767 @Override 768 @CheckForNull 769 protected E computeNext() { 770 if (itr1.hasNext()) { 771 return itr1.next(); 772 } 773 while (itr2.hasNext()) { 774 E e = itr2.next(); 775 if (!set1.contains(e)) { 776 return e; 777 } 778 } 779 return endOfData(); 780 } 781 }; 782 } 783 784 @Override 785 public Stream<E> stream() { 786 return Stream.concat(set1.stream(), set2.stream().filter((E e) -> !set1.contains(e))); 787 } 788 789 @Override 790 public Stream<E> parallelStream() { 791 return stream().parallel(); 792 } 793 794 @Override 795 public boolean contains(@CheckForNull Object object) { 796 return set1.contains(object) || set2.contains(object); 797 } 798 799 @Override 800 public <S extends Set<E>> S copyInto(S set) { 801 set.addAll(set1); 802 set.addAll(set2); 803 return set; 804 } 805 806 @Override 807 @SuppressWarnings({"nullness", "unchecked"}) // see supertype 808 public ImmutableSet<@NonNull E> immutableCopy() { 809 ImmutableSet.Builder<@NonNull E> builder = 810 new ImmutableSet.Builder<@NonNull E>() 811 .addAll((Iterable<@NonNull E>) set1) 812 .addAll((Iterable<@NonNull E>) set2); 813 return (ImmutableSet<@NonNull E>) builder.build(); 814 } 815 }; 816 } 817 818 /** 819 * Returns an unmodifiable <b>view</b> of the intersection of two sets. The returned set contains 820 * all elements that are contained by both backing sets. The iteration order of the returned set 821 * matches that of {@code set1}. 822 * 823 * <p>Results are undefined if {@code set1} and {@code set2} are sets based on different 824 * equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a 825 * {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}. 826 * 827 * <p><b>Note:</b> The returned view performs slightly better when {@code set1} is the smaller of 828 * the two sets. If you have reason to believe one of your sets will generally be smaller than the 829 * other, pass it first. Unfortunately, since this method sets the generic type of the returned 830 * set based on the type of the first set passed, this could in rare cases force you to make a 831 * cast, for example: 832 * 833 * <pre>{@code 834 * Set<Object> aFewBadObjects = ... 835 * Set<String> manyBadStrings = ... 836 * 837 * // impossible for a non-String to be in the intersection 838 * SuppressWarnings("unchecked") 839 * Set<String> badStrings = (Set) Sets.intersection( 840 * aFewBadObjects, manyBadStrings); 841 * }</pre> 842 * 843 * <p>This is unfortunate, but should come up only very rarely. 844 */ 845 public static <E extends @Nullable Object> SetView<E> intersection( 846 final Set<E> set1, final Set<?> set2) { 847 checkNotNull(set1, "set1"); 848 checkNotNull(set2, "set2"); 849 850 return new SetView<E>() { 851 @Override 852 public UnmodifiableIterator<E> iterator() { 853 return new AbstractIterator<E>() { 854 final Iterator<E> itr = set1.iterator(); 855 856 @Override 857 @CheckForNull 858 protected E computeNext() { 859 while (itr.hasNext()) { 860 E e = itr.next(); 861 if (set2.contains(e)) { 862 return e; 863 } 864 } 865 return endOfData(); 866 } 867 }; 868 } 869 870 @Override 871 public Stream<E> stream() { 872 return set1.stream().filter(set2::contains); 873 } 874 875 @Override 876 public Stream<E> parallelStream() { 877 return set1.parallelStream().filter(set2::contains); 878 } 879 880 @Override 881 public int size() { 882 int size = 0; 883 for (E e : set1) { 884 if (set2.contains(e)) { 885 size++; 886 } 887 } 888 return size; 889 } 890 891 @Override 892 public boolean isEmpty() { 893 return Collections.disjoint(set2, set1); 894 } 895 896 @Override 897 public boolean contains(@CheckForNull Object object) { 898 return set1.contains(object) && set2.contains(object); 899 } 900 901 @Override 902 public boolean containsAll(Collection<?> collection) { 903 return set1.containsAll(collection) && set2.containsAll(collection); 904 } 905 }; 906 } 907 908 /** 909 * Returns an unmodifiable <b>view</b> of the difference of two sets. The returned set contains 910 * all elements that are contained by {@code set1} and not contained by {@code set2}. {@code set2} 911 * may also contain elements not present in {@code set1}; these are simply ignored. The iteration 912 * order of the returned set matches that of {@code set1}. 913 * 914 * <p>Results are undefined if {@code set1} and {@code set2} are sets based on different 915 * equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a 916 * {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}. 917 */ 918 public static <E extends @Nullable Object> SetView<E> difference( 919 final Set<E> set1, final Set<?> set2) { 920 checkNotNull(set1, "set1"); 921 checkNotNull(set2, "set2"); 922 923 return new SetView<E>() { 924 @Override 925 public UnmodifiableIterator<E> iterator() { 926 return new AbstractIterator<E>() { 927 final Iterator<E> itr = set1.iterator(); 928 929 @Override 930 @CheckForNull 931 protected E computeNext() { 932 while (itr.hasNext()) { 933 E e = itr.next(); 934 if (!set2.contains(e)) { 935 return e; 936 } 937 } 938 return endOfData(); 939 } 940 }; 941 } 942 943 @Override 944 public Stream<E> stream() { 945 return set1.stream().filter(e -> !set2.contains(e)); 946 } 947 948 @Override 949 public Stream<E> parallelStream() { 950 return set1.parallelStream().filter(e -> !set2.contains(e)); 951 } 952 953 @Override 954 public int size() { 955 int size = 0; 956 for (E e : set1) { 957 if (!set2.contains(e)) { 958 size++; 959 } 960 } 961 return size; 962 } 963 964 @Override 965 public boolean isEmpty() { 966 return set2.containsAll(set1); 967 } 968 969 @Override 970 public boolean contains(@CheckForNull Object element) { 971 return set1.contains(element) && !set2.contains(element); 972 } 973 }; 974 } 975 976 /** 977 * Returns an unmodifiable <b>view</b> of the symmetric difference of two sets. The returned set 978 * contains all elements that are contained in either {@code set1} or {@code set2} but not in 979 * both. The iteration order of the returned set is undefined. 980 * 981 * <p>Results are undefined if {@code set1} and {@code set2} are sets based on different 982 * equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a 983 * {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}. 984 * 985 * @since 3.0 986 */ 987 public static <E extends @Nullable Object> SetView<E> symmetricDifference( 988 final Set<? extends E> set1, final Set<? extends E> set2) { 989 checkNotNull(set1, "set1"); 990 checkNotNull(set2, "set2"); 991 992 return new SetView<E>() { 993 @Override 994 public UnmodifiableIterator<E> iterator() { 995 final Iterator<? extends E> itr1 = set1.iterator(); 996 final Iterator<? extends E> itr2 = set2.iterator(); 997 return new AbstractIterator<E>() { 998 @Override 999 @CheckForNull 1000 public E computeNext() { 1001 while (itr1.hasNext()) { 1002 E elem1 = itr1.next(); 1003 if (!set2.contains(elem1)) { 1004 return elem1; 1005 } 1006 } 1007 while (itr2.hasNext()) { 1008 E elem2 = itr2.next(); 1009 if (!set1.contains(elem2)) { 1010 return elem2; 1011 } 1012 } 1013 return endOfData(); 1014 } 1015 }; 1016 } 1017 1018 @Override 1019 public int size() { 1020 int size = 0; 1021 for (E e : set1) { 1022 if (!set2.contains(e)) { 1023 size++; 1024 } 1025 } 1026 for (E e : set2) { 1027 if (!set1.contains(e)) { 1028 size++; 1029 } 1030 } 1031 return size; 1032 } 1033 1034 @Override 1035 public boolean isEmpty() { 1036 return set1.equals(set2); 1037 } 1038 1039 @Override 1040 public boolean contains(@CheckForNull Object element) { 1041 return set1.contains(element) ^ set2.contains(element); 1042 } 1043 }; 1044 } 1045 1046 /** 1047 * Returns the elements of {@code unfiltered} that satisfy a predicate. The returned set is a live 1048 * view of {@code unfiltered}; changes to one affect the other. 1049 * 1050 * <p>The resulting set's iterator does not support {@code remove()}, but all other set methods 1051 * are supported. When given an element that doesn't satisfy the predicate, the set's {@code 1052 * add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods 1053 * such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements 1054 * that satisfy the filter will be removed from the underlying set. 1055 * 1056 * <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is. 1057 * 1058 * <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in 1059 * the underlying set and determine which elements satisfy the filter. When a live view is 1060 * <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and 1061 * use the copy. 1062 * 1063 * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at 1064 * {@link Predicate#apply}. Do not provide a predicate such as {@code 1065 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link 1066 * Iterables#filter(Iterable, Class)} for related functionality.) 1067 * 1068 * <p><b>Java 8+ users:</b> many use cases for this method are better addressed by {@link 1069 * java.util.stream.Stream#filter}. This method is not being deprecated, but we gently encourage 1070 * you to migrate to streams. 1071 */ 1072 // TODO(kevinb): how to omit that last sentence when building GWT javadoc? 1073 public static <E extends @Nullable Object> Set<E> filter( 1074 Set<E> unfiltered, Predicate<? super E> predicate) { 1075 if (unfiltered instanceof SortedSet) { 1076 return filter((SortedSet<E>) unfiltered, predicate); 1077 } 1078 if (unfiltered instanceof FilteredSet) { 1079 // Support clear(), removeAll(), and retainAll() when filtering a filtered 1080 // collection. 1081 FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; 1082 Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate); 1083 return new FilteredSet<>((Set<E>) filtered.unfiltered, combinedPredicate); 1084 } 1085 1086 return new FilteredSet<>(checkNotNull(unfiltered), checkNotNull(predicate)); 1087 } 1088 1089 /** 1090 * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that satisfy a predicate. The 1091 * returned set is a live view of {@code unfiltered}; changes to one affect the other. 1092 * 1093 * <p>The resulting set's iterator does not support {@code remove()}, but all other set methods 1094 * are supported. When given an element that doesn't satisfy the predicate, the set's {@code 1095 * add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods 1096 * such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements 1097 * that satisfy the filter will be removed from the underlying set. 1098 * 1099 * <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is. 1100 * 1101 * <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in 1102 * the underlying set and determine which elements satisfy the filter. When a live view is 1103 * <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and 1104 * use the copy. 1105 * 1106 * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at 1107 * {@link Predicate#apply}. Do not provide a predicate such as {@code 1108 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link 1109 * Iterables#filter(Iterable, Class)} for related functionality.) 1110 * 1111 * @since 11.0 1112 */ 1113 public static <E extends @Nullable Object> SortedSet<E> filter( 1114 SortedSet<E> unfiltered, Predicate<? super E> predicate) { 1115 if (unfiltered instanceof FilteredSet) { 1116 // Support clear(), removeAll(), and retainAll() when filtering a filtered 1117 // collection. 1118 FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; 1119 Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate); 1120 return new FilteredSortedSet<>((SortedSet<E>) filtered.unfiltered, combinedPredicate); 1121 } 1122 1123 return new FilteredSortedSet<>(checkNotNull(unfiltered), checkNotNull(predicate)); 1124 } 1125 1126 /** 1127 * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that satisfy a predicate. 1128 * The returned set is a live view of {@code unfiltered}; changes to one affect the other. 1129 * 1130 * <p>The resulting set's iterator does not support {@code remove()}, but all other set methods 1131 * are supported. When given an element that doesn't satisfy the predicate, the set's {@code 1132 * add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods 1133 * such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements 1134 * that satisfy the filter will be removed from the underlying set. 1135 * 1136 * <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is. 1137 * 1138 * <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in 1139 * the underlying set and determine which elements satisfy the filter. When a live view is 1140 * <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and 1141 * use the copy. 1142 * 1143 * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at 1144 * {@link Predicate#apply}. Do not provide a predicate such as {@code 1145 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link 1146 * Iterables#filter(Iterable, Class)} for related functionality.) 1147 * 1148 * @since 14.0 1149 */ 1150 @GwtIncompatible // NavigableSet 1151 public static <E extends @Nullable Object> NavigableSet<E> filter( 1152 NavigableSet<E> unfiltered, Predicate<? super E> predicate) { 1153 if (unfiltered instanceof FilteredSet) { 1154 // Support clear(), removeAll(), and retainAll() when filtering a filtered 1155 // collection. 1156 FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; 1157 Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate); 1158 return new FilteredNavigableSet<>((NavigableSet<E>) filtered.unfiltered, combinedPredicate); 1159 } 1160 1161 return new FilteredNavigableSet<>(checkNotNull(unfiltered), checkNotNull(predicate)); 1162 } 1163 1164 private static class FilteredSet<E extends @Nullable Object> extends FilteredCollection<E> 1165 implements Set<E> { 1166 FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) { 1167 super(unfiltered, predicate); 1168 } 1169 1170 @Override 1171 public boolean equals(@CheckForNull Object object) { 1172 return equalsImpl(this, object); 1173 } 1174 1175 @Override 1176 public int hashCode() { 1177 return hashCodeImpl(this); 1178 } 1179 } 1180 1181 private static class FilteredSortedSet<E extends @Nullable Object> extends FilteredSet<E> 1182 implements SortedSet<E> { 1183 1184 FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) { 1185 super(unfiltered, predicate); 1186 } 1187 1188 @Override 1189 @CheckForNull 1190 public Comparator<? super E> comparator() { 1191 return ((SortedSet<E>) unfiltered).comparator(); 1192 } 1193 1194 @Override 1195 public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) { 1196 return new FilteredSortedSet<>( 1197 ((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate); 1198 } 1199 1200 @Override 1201 public SortedSet<E> headSet(@ParametricNullness E toElement) { 1202 return new FilteredSortedSet<>(((SortedSet<E>) unfiltered).headSet(toElement), predicate); 1203 } 1204 1205 @Override 1206 public SortedSet<E> tailSet(@ParametricNullness E fromElement) { 1207 return new FilteredSortedSet<>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate); 1208 } 1209 1210 @Override 1211 @ParametricNullness 1212 public E first() { 1213 return Iterators.find(unfiltered.iterator(), predicate); 1214 } 1215 1216 @Override 1217 @ParametricNullness 1218 public E last() { 1219 SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered; 1220 while (true) { 1221 E element = sortedUnfiltered.last(); 1222 if (predicate.apply(element)) { 1223 return element; 1224 } 1225 sortedUnfiltered = sortedUnfiltered.headSet(element); 1226 } 1227 } 1228 } 1229 1230 @GwtIncompatible // NavigableSet 1231 private static class FilteredNavigableSet<E extends @Nullable Object> extends FilteredSortedSet<E> 1232 implements NavigableSet<E> { 1233 FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) { 1234 super(unfiltered, predicate); 1235 } 1236 1237 NavigableSet<E> unfiltered() { 1238 return (NavigableSet<E>) unfiltered; 1239 } 1240 1241 @Override 1242 @CheckForNull 1243 public E lower(@ParametricNullness E e) { 1244 return Iterators.find(unfiltered().headSet(e, false).descendingIterator(), predicate, null); 1245 } 1246 1247 @Override 1248 @CheckForNull 1249 public E floor(@ParametricNullness E e) { 1250 return Iterators.find(unfiltered().headSet(e, true).descendingIterator(), predicate, null); 1251 } 1252 1253 @Override 1254 @CheckForNull 1255 public E ceiling(@ParametricNullness E e) { 1256 return Iterables.find(unfiltered().tailSet(e, true), predicate, null); 1257 } 1258 1259 @Override 1260 @CheckForNull 1261 public E higher(@ParametricNullness E e) { 1262 return Iterables.find(unfiltered().tailSet(e, false), predicate, null); 1263 } 1264 1265 @Override 1266 @CheckForNull 1267 public E pollFirst() { 1268 return Iterables.removeFirstMatching(unfiltered(), predicate); 1269 } 1270 1271 @Override 1272 @CheckForNull 1273 public E pollLast() { 1274 return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate); 1275 } 1276 1277 @Override 1278 public NavigableSet<E> descendingSet() { 1279 return Sets.filter(unfiltered().descendingSet(), predicate); 1280 } 1281 1282 @Override 1283 public Iterator<E> descendingIterator() { 1284 return Iterators.filter(unfiltered().descendingIterator(), predicate); 1285 } 1286 1287 @Override 1288 @ParametricNullness 1289 public E last() { 1290 return Iterators.find(unfiltered().descendingIterator(), predicate); 1291 } 1292 1293 @Override 1294 public NavigableSet<E> subSet( 1295 @ParametricNullness E fromElement, 1296 boolean fromInclusive, 1297 @ParametricNullness E toElement, 1298 boolean toInclusive) { 1299 return filter( 1300 unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate); 1301 } 1302 1303 @Override 1304 public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) { 1305 return filter(unfiltered().headSet(toElement, inclusive), predicate); 1306 } 1307 1308 @Override 1309 public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) { 1310 return filter(unfiltered().tailSet(fromElement, inclusive), predicate); 1311 } 1312 } 1313 1314 /** 1315 * Returns every possible list that can be formed by choosing one element from each of the given 1316 * sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian 1317 * product</a>" of the sets. For example: 1318 * 1319 * <pre>{@code 1320 * Sets.cartesianProduct(ImmutableList.of( 1321 * ImmutableSet.of(1, 2), 1322 * ImmutableSet.of("A", "B", "C"))) 1323 * }</pre> 1324 * 1325 * <p>returns a set containing six lists: 1326 * 1327 * <ul> 1328 * <li>{@code ImmutableList.of(1, "A")} 1329 * <li>{@code ImmutableList.of(1, "B")} 1330 * <li>{@code ImmutableList.of(1, "C")} 1331 * <li>{@code ImmutableList.of(2, "A")} 1332 * <li>{@code ImmutableList.of(2, "B")} 1333 * <li>{@code ImmutableList.of(2, "C")} 1334 * </ul> 1335 * 1336 * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian 1337 * products that you would get from nesting for loops: 1338 * 1339 * <pre>{@code 1340 * for (B b0 : sets.get(0)) { 1341 * for (B b1 : sets.get(1)) { 1342 * ... 1343 * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); 1344 * // operate on tuple 1345 * } 1346 * } 1347 * }</pre> 1348 * 1349 * <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at 1350 * all are provided (an empty list), the resulting Cartesian product has one element, an empty 1351 * list (counter-intuitive, but mathematically consistent). 1352 * 1353 * <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a 1354 * set of size {@code m x n x p}, its actual memory consumption is much smaller. When the 1355 * cartesian set is constructed, the input sets are merely copied. Only as the resulting set is 1356 * iterated are the individual lists created, and these are not retained after iteration. 1357 * 1358 * @param sets the sets to choose elements from, in the order that the elements chosen from those 1359 * sets should appear in the resulting lists 1360 * @param <B> any common base class shared by all axes (often just {@link Object}) 1361 * @return the Cartesian product, as an immutable set containing immutable lists 1362 * @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a 1363 * provided set is null 1364 * @throws IllegalArgumentException if the cartesian product size exceeds the {@code int} range 1365 * @since 2.0 1366 */ 1367 public static <B> Set<List<B>> cartesianProduct(List<? extends Set<? extends B>> sets) { 1368 return CartesianSet.create(sets); 1369 } 1370 1371 /** 1372 * Returns every possible list that can be formed by choosing one element from each of the given 1373 * sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian 1374 * product</a>" of the sets. For example: 1375 * 1376 * <pre>{@code 1377 * Sets.cartesianProduct( 1378 * ImmutableSet.of(1, 2), 1379 * ImmutableSet.of("A", "B", "C")) 1380 * }</pre> 1381 * 1382 * <p>returns a set containing six lists: 1383 * 1384 * <ul> 1385 * <li>{@code ImmutableList.of(1, "A")} 1386 * <li>{@code ImmutableList.of(1, "B")} 1387 * <li>{@code ImmutableList.of(1, "C")} 1388 * <li>{@code ImmutableList.of(2, "A")} 1389 * <li>{@code ImmutableList.of(2, "B")} 1390 * <li>{@code ImmutableList.of(2, "C")} 1391 * </ul> 1392 * 1393 * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian 1394 * products that you would get from nesting for loops: 1395 * 1396 * <pre>{@code 1397 * for (B b0 : sets.get(0)) { 1398 * for (B b1 : sets.get(1)) { 1399 * ... 1400 * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); 1401 * // operate on tuple 1402 * } 1403 * } 1404 * }</pre> 1405 * 1406 * <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at 1407 * all are provided (an empty list), the resulting Cartesian product has one element, an empty 1408 * list (counter-intuitive, but mathematically consistent). 1409 * 1410 * <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a 1411 * set of size {@code m x n x p}, its actual memory consumption is much smaller. When the 1412 * cartesian set is constructed, the input sets are merely copied. Only as the resulting set is 1413 * iterated are the individual lists created, and these are not retained after iteration. 1414 * 1415 * @param sets the sets to choose elements from, in the order that the elements chosen from those 1416 * sets should appear in the resulting lists 1417 * @param <B> any common base class shared by all axes (often just {@link Object}) 1418 * @return the Cartesian product, as an immutable set containing immutable lists 1419 * @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a 1420 * provided set is null 1421 * @throws IllegalArgumentException if the cartesian product size exceeds the {@code int} range 1422 * @since 2.0 1423 */ 1424 @SafeVarargs 1425 public static <B> Set<List<B>> cartesianProduct(Set<? extends B>... sets) { 1426 return cartesianProduct(Arrays.asList(sets)); 1427 } 1428 1429 private static final class CartesianSet<E> extends ForwardingCollection<List<E>> 1430 implements Set<List<E>> { 1431 private final transient ImmutableList<ImmutableSet<E>> axes; 1432 private final transient CartesianList<E> delegate; 1433 1434 static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) { 1435 ImmutableList.Builder<ImmutableSet<E>> axesBuilder = new ImmutableList.Builder<>(sets.size()); 1436 for (Set<? extends E> set : sets) { 1437 ImmutableSet<E> copy = ImmutableSet.copyOf(set); 1438 if (copy.isEmpty()) { 1439 return ImmutableSet.of(); 1440 } 1441 axesBuilder.add(copy); 1442 } 1443 final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build(); 1444 ImmutableList<List<E>> listAxes = 1445 new ImmutableList<List<E>>() { 1446 @Override 1447 public int size() { 1448 return axes.size(); 1449 } 1450 1451 @Override 1452 public List<E> get(int index) { 1453 return axes.get(index).asList(); 1454 } 1455 1456 @Override 1457 boolean isPartialView() { 1458 return true; 1459 } 1460 1461 // redeclare to help optimizers with b/310253115 1462 @SuppressWarnings("RedundantOverride") 1463 @Override 1464 @J2ktIncompatible // serialization 1465 @GwtIncompatible // serialization 1466 Object writeReplace() { 1467 return super.writeReplace(); 1468 } 1469 }; 1470 return new CartesianSet<E>(axes, new CartesianList<E>(listAxes)); 1471 } 1472 1473 private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) { 1474 this.axes = axes; 1475 this.delegate = delegate; 1476 } 1477 1478 @Override 1479 protected Collection<List<E>> delegate() { 1480 return delegate; 1481 } 1482 1483 @Override 1484 public boolean contains(@CheckForNull Object object) { 1485 if (!(object instanceof List)) { 1486 return false; 1487 } 1488 List<?> list = (List<?>) object; 1489 if (list.size() != axes.size()) { 1490 return false; 1491 } 1492 int i = 0; 1493 for (Object o : list) { 1494 if (!axes.get(i).contains(o)) { 1495 return false; 1496 } 1497 i++; 1498 } 1499 return true; 1500 } 1501 1502 @Override 1503 public boolean equals(@CheckForNull Object object) { 1504 // Warning: this is broken if size() == 0, so it is critical that we 1505 // substitute an empty ImmutableSet to the user in place of this 1506 if (object instanceof CartesianSet) { 1507 CartesianSet<?> that = (CartesianSet<?>) object; 1508 return this.axes.equals(that.axes); 1509 } 1510 if (object instanceof Set) { 1511 Set<?> that = (Set<?>) object; 1512 return this.size() == that.size() && this.containsAll(that); 1513 } 1514 return false; 1515 } 1516 1517 @Override 1518 public int hashCode() { 1519 // Warning: this is broken if size() == 0, so it is critical that we 1520 // substitute an empty ImmutableSet to the user in place of this 1521 1522 // It's a weird formula, but tests prove it works. 1523 int adjust = size() - 1; 1524 for (int i = 0; i < axes.size(); i++) { 1525 adjust *= 31; 1526 adjust = ~~adjust; 1527 // in GWT, we have to deal with integer overflow carefully 1528 } 1529 int hash = 1; 1530 for (Set<E> axis : axes) { 1531 hash = 31 * hash + (size() / axis.size() * axis.hashCode()); 1532 1533 hash = ~~hash; 1534 } 1535 hash += adjust; 1536 return ~~hash; 1537 } 1538 } 1539 1540 /** 1541 * Returns the set of all possible subsets of {@code set}. For example, {@code 1542 * powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, {1}, {2}, {1, 2}}}. 1543 * 1544 * <p>Elements appear in these subsets in the same iteration order as they appeared in the input 1545 * set. The order in which these subsets appear in the outer set is undefined. Note that the power 1546 * set of the empty set is not the empty set, but a one-element set containing the empty set. 1547 * 1548 * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements 1549 * are identical, even if the input set uses a different concept of equivalence. 1550 * 1551 * <p><i>Performance notes:</i> while the power set of a set with size {@code n} is of size {@code 1552 * 2^n}, its memory usage is only {@code O(n)}. When the power set is constructed, the input set 1553 * is merely copied. Only as the power set is iterated are the individual subsets created, and 1554 * these subsets themselves occupy only a small constant amount of memory. 1555 * 1556 * @param set the set of elements to construct a power set from 1557 * @return the power set, as an immutable set of immutable sets 1558 * @throws IllegalArgumentException if {@code set} has more than 30 unique elements (causing the 1559 * power set size to exceed the {@code int} range) 1560 * @throws NullPointerException if {@code set} is or contains {@code null} 1561 * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at Wikipedia</a> 1562 * @since 4.0 1563 */ 1564 @GwtCompatible(serializable = false) 1565 public static <E> Set<Set<E>> powerSet(Set<E> set) { 1566 return new PowerSet<E>(set); 1567 } 1568 1569 private static final class SubSet<E> extends AbstractSet<E> { 1570 private final ImmutableMap<E, Integer> inputSet; 1571 private final int mask; 1572 1573 SubSet(ImmutableMap<E, Integer> inputSet, int mask) { 1574 this.inputSet = inputSet; 1575 this.mask = mask; 1576 } 1577 1578 @Override 1579 public Iterator<E> iterator() { 1580 return new UnmodifiableIterator<E>() { 1581 final ImmutableList<E> elements = inputSet.keySet().asList(); 1582 int remainingSetBits = mask; 1583 1584 @Override 1585 public boolean hasNext() { 1586 return remainingSetBits != 0; 1587 } 1588 1589 @Override 1590 public E next() { 1591 int index = Integer.numberOfTrailingZeros(remainingSetBits); 1592 if (index == 32) { 1593 throw new NoSuchElementException(); 1594 } 1595 remainingSetBits &= ~(1 << index); 1596 return elements.get(index); 1597 } 1598 }; 1599 } 1600 1601 @Override 1602 public int size() { 1603 return Integer.bitCount(mask); 1604 } 1605 1606 @Override 1607 public boolean contains(@CheckForNull Object o) { 1608 Integer index = inputSet.get(o); 1609 return index != null && (mask & (1 << index)) != 0; 1610 } 1611 } 1612 1613 private static final class PowerSet<E> extends AbstractSet<Set<E>> { 1614 final ImmutableMap<E, Integer> inputSet; 1615 1616 PowerSet(Set<E> input) { 1617 checkArgument( 1618 input.size() <= 30, "Too many elements to create power set: %s > 30", input.size()); 1619 this.inputSet = Maps.indexMap(input); 1620 } 1621 1622 @Override 1623 public int size() { 1624 return 1 << inputSet.size(); 1625 } 1626 1627 @Override 1628 public boolean isEmpty() { 1629 return false; 1630 } 1631 1632 @Override 1633 public Iterator<Set<E>> iterator() { 1634 return new AbstractIndexedListIterator<Set<E>>(size()) { 1635 @Override 1636 protected Set<E> get(final int setBits) { 1637 return new SubSet<>(inputSet, setBits); 1638 } 1639 }; 1640 } 1641 1642 @Override 1643 public boolean contains(@CheckForNull Object obj) { 1644 if (obj instanceof Set) { 1645 Set<?> set = (Set<?>) obj; 1646 return inputSet.keySet().containsAll(set); 1647 } 1648 return false; 1649 } 1650 1651 @Override 1652 public boolean equals(@CheckForNull Object obj) { 1653 if (obj instanceof PowerSet) { 1654 PowerSet<?> that = (PowerSet<?>) obj; 1655 return inputSet.keySet().equals(that.inputSet.keySet()); 1656 } 1657 return super.equals(obj); 1658 } 1659 1660 @Override 1661 public int hashCode() { 1662 /* 1663 * The sum of the sums of the hash codes in each subset is just the sum of 1664 * each input element's hash code times the number of sets that element 1665 * appears in. Each element appears in exactly half of the 2^n sets, so: 1666 */ 1667 return inputSet.keySet().hashCode() << (inputSet.size() - 1); 1668 } 1669 1670 @Override 1671 public String toString() { 1672 return "powerSet(" + inputSet + ")"; 1673 } 1674 } 1675 1676 /** 1677 * Returns the set of all subsets of {@code set} of size {@code size}. For example, {@code 1678 * combinations(ImmutableSet.of(1, 2, 3), 2)} returns the set {@code {{1, 2}, {1, 3}, {2, 3}}}. 1679 * 1680 * <p>Elements appear in these subsets in the same iteration order as they appeared in the input 1681 * set. The order in which these subsets appear in the outer set is undefined. 1682 * 1683 * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements 1684 * are identical, even if the input set uses a different concept of equivalence. 1685 * 1686 * <p><i>Performance notes:</i> the memory usage of the returned set is only {@code O(n)}. When 1687 * the result set is constructed, the input set is merely copied. Only as the result set is 1688 * iterated are the individual subsets created. Each of these subsets occupies an additional O(n) 1689 * memory but only for as long as the user retains a reference to it. That is, the set returned by 1690 * {@code combinations} does not retain the individual subsets. 1691 * 1692 * @param set the set of elements to take combinations of 1693 * @param size the number of elements per combination 1694 * @return the set of all combinations of {@code size} elements from {@code set} 1695 * @throws IllegalArgumentException if {@code size} is not between 0 and {@code set.size()} 1696 * inclusive 1697 * @throws NullPointerException if {@code set} is or contains {@code null} 1698 * @since 23.0 1699 */ 1700 public static <E> Set<Set<E>> combinations(Set<E> set, final int size) { 1701 final ImmutableMap<E, Integer> index = Maps.indexMap(set); 1702 checkNonnegative(size, "size"); 1703 checkArgument(size <= index.size(), "size (%s) must be <= set.size() (%s)", size, index.size()); 1704 if (size == 0) { 1705 return ImmutableSet.<Set<E>>of(ImmutableSet.<E>of()); 1706 } else if (size == index.size()) { 1707 return ImmutableSet.<Set<E>>of(index.keySet()); 1708 } 1709 return new AbstractSet<Set<E>>() { 1710 @Override 1711 public boolean contains(@CheckForNull Object o) { 1712 if (o instanceof Set) { 1713 Set<?> s = (Set<?>) o; 1714 return s.size() == size && index.keySet().containsAll(s); 1715 } 1716 return false; 1717 } 1718 1719 @Override 1720 public Iterator<Set<E>> iterator() { 1721 return new AbstractIterator<Set<E>>() { 1722 final BitSet bits = new BitSet(index.size()); 1723 1724 @Override 1725 @CheckForNull 1726 protected Set<E> computeNext() { 1727 if (bits.isEmpty()) { 1728 bits.set(0, size); 1729 } else { 1730 int firstSetBit = bits.nextSetBit(0); 1731 int bitToFlip = bits.nextClearBit(firstSetBit); 1732 1733 if (bitToFlip == index.size()) { 1734 return endOfData(); 1735 } 1736 1737 /* 1738 * The current set in sorted order looks like 1739 * {firstSetBit, firstSetBit + 1, ..., bitToFlip - 1, ...} 1740 * where it does *not* contain bitToFlip. 1741 * 1742 * The next combination is 1743 * 1744 * {0, 1, ..., bitToFlip - firstSetBit - 2, bitToFlip, ...} 1745 * 1746 * This is lexicographically next if you look at the combinations in descending order 1747 * e.g. {2, 1, 0}, {3, 1, 0}, {3, 2, 0}, {3, 2, 1}, {4, 1, 0}... 1748 */ 1749 1750 bits.set(0, bitToFlip - firstSetBit - 1); 1751 bits.clear(bitToFlip - firstSetBit - 1, bitToFlip); 1752 bits.set(bitToFlip); 1753 } 1754 final BitSet copy = (BitSet) bits.clone(); 1755 return new AbstractSet<E>() { 1756 @Override 1757 public boolean contains(@CheckForNull Object o) { 1758 Integer i = index.get(o); 1759 return i != null && copy.get(i); 1760 } 1761 1762 @Override 1763 public Iterator<E> iterator() { 1764 return new AbstractIterator<E>() { 1765 int i = -1; 1766 1767 @Override 1768 @CheckForNull 1769 protected E computeNext() { 1770 i = copy.nextSetBit(i + 1); 1771 if (i == -1) { 1772 return endOfData(); 1773 } 1774 return index.keySet().asList().get(i); 1775 } 1776 }; 1777 } 1778 1779 @Override 1780 public int size() { 1781 return size; 1782 } 1783 }; 1784 } 1785 }; 1786 } 1787 1788 @Override 1789 public int size() { 1790 return IntMath.binomial(index.size(), size); 1791 } 1792 1793 @Override 1794 public String toString() { 1795 return "Sets.combinations(" + index.keySet() + ", " + size + ")"; 1796 } 1797 }; 1798 } 1799 1800 /** An implementation for {@link Set#hashCode()}. */ 1801 static int hashCodeImpl(Set<?> s) { 1802 int hashCode = 0; 1803 for (Object o : s) { 1804 hashCode += o != null ? o.hashCode() : 0; 1805 1806 hashCode = ~~hashCode; 1807 // Needed to deal with unusual integer overflow in GWT. 1808 } 1809 return hashCode; 1810 } 1811 1812 /** An implementation for {@link Set#equals(Object)}. */ 1813 static boolean equalsImpl(Set<?> s, @CheckForNull Object object) { 1814 if (s == object) { 1815 return true; 1816 } 1817 if (object instanceof Set) { 1818 Set<?> o = (Set<?>) object; 1819 1820 try { 1821 return s.size() == o.size() && s.containsAll(o); 1822 } catch (NullPointerException | ClassCastException ignored) { 1823 return false; 1824 } 1825 } 1826 return false; 1827 } 1828 1829 /** 1830 * Returns an unmodifiable view of the specified navigable set. This method allows modules to 1831 * provide users with "read-only" access to internal navigable sets. Query operations on the 1832 * returned set "read through" to the specified set, and attempts to modify the returned set, 1833 * whether direct or via its collection views, result in an {@code UnsupportedOperationException}. 1834 * 1835 * <p>The returned navigable set will be serializable if the specified navigable set is 1836 * serializable. 1837 * 1838 * <p><b>Java 8+ users and later:</b> Prefer {@link Collections#unmodifiableNavigableSet}. 1839 * 1840 * @param set the navigable set for which an unmodifiable view is to be returned 1841 * @return an unmodifiable view of the specified navigable set 1842 * @since 12.0 1843 */ 1844 public static <E extends @Nullable Object> NavigableSet<E> unmodifiableNavigableSet( 1845 NavigableSet<E> set) { 1846 if (set instanceof ImmutableCollection || set instanceof UnmodifiableNavigableSet) { 1847 return set; 1848 } 1849 return new UnmodifiableNavigableSet<>(set); 1850 } 1851 1852 static final class UnmodifiableNavigableSet<E extends @Nullable Object> 1853 extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable { 1854 private final NavigableSet<E> delegate; 1855 private final SortedSet<E> unmodifiableDelegate; 1856 1857 UnmodifiableNavigableSet(NavigableSet<E> delegate) { 1858 this.delegate = checkNotNull(delegate); 1859 this.unmodifiableDelegate = Collections.unmodifiableSortedSet(delegate); 1860 } 1861 1862 @Override 1863 protected SortedSet<E> delegate() { 1864 return unmodifiableDelegate; 1865 } 1866 1867 // default methods not forwarded by ForwardingSortedSet 1868 1869 @Override 1870 public boolean removeIf(java.util.function.Predicate<? super E> filter) { 1871 throw new UnsupportedOperationException(); 1872 } 1873 1874 @Override 1875 public Stream<E> stream() { 1876 return delegate.stream(); 1877 } 1878 1879 @Override 1880 public Stream<E> parallelStream() { 1881 return delegate.parallelStream(); 1882 } 1883 1884 @Override 1885 public void forEach(Consumer<? super E> action) { 1886 delegate.forEach(action); 1887 } 1888 1889 @Override 1890 @CheckForNull 1891 public E lower(@ParametricNullness E e) { 1892 return delegate.lower(e); 1893 } 1894 1895 @Override 1896 @CheckForNull 1897 public E floor(@ParametricNullness E e) { 1898 return delegate.floor(e); 1899 } 1900 1901 @Override 1902 @CheckForNull 1903 public E ceiling(@ParametricNullness E e) { 1904 return delegate.ceiling(e); 1905 } 1906 1907 @Override 1908 @CheckForNull 1909 public E higher(@ParametricNullness E e) { 1910 return delegate.higher(e); 1911 } 1912 1913 @Override 1914 @CheckForNull 1915 public E pollFirst() { 1916 throw new UnsupportedOperationException(); 1917 } 1918 1919 @Override 1920 @CheckForNull 1921 public E pollLast() { 1922 throw new UnsupportedOperationException(); 1923 } 1924 1925 @LazyInit @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet; 1926 1927 @Override 1928 public NavigableSet<E> descendingSet() { 1929 UnmodifiableNavigableSet<E> result = descendingSet; 1930 if (result == null) { 1931 result = descendingSet = new UnmodifiableNavigableSet<>(delegate.descendingSet()); 1932 result.descendingSet = this; 1933 } 1934 return result; 1935 } 1936 1937 @Override 1938 public Iterator<E> descendingIterator() { 1939 return Iterators.unmodifiableIterator(delegate.descendingIterator()); 1940 } 1941 1942 @Override 1943 public NavigableSet<E> subSet( 1944 @ParametricNullness E fromElement, 1945 boolean fromInclusive, 1946 @ParametricNullness E toElement, 1947 boolean toInclusive) { 1948 return unmodifiableNavigableSet( 1949 delegate.subSet(fromElement, fromInclusive, toElement, toInclusive)); 1950 } 1951 1952 @Override 1953 public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) { 1954 return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive)); 1955 } 1956 1957 @Override 1958 public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) { 1959 return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive)); 1960 } 1961 1962 private static final long serialVersionUID = 0; 1963 } 1964 1965 /** 1966 * Returns a synchronized (thread-safe) navigable set backed by the specified navigable set. In 1967 * order to guarantee serial access, it is critical that <b>all</b> access to the backing 1968 * navigable set is accomplished through the returned navigable set (or its views). 1969 * 1970 * <p>It is imperative that the user manually synchronize on the returned sorted set when 1971 * iterating over it or any of its {@code descendingSet}, {@code subSet}, {@code headSet}, or 1972 * {@code tailSet} views. 1973 * 1974 * <pre>{@code 1975 * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); 1976 * ... 1977 * synchronized (set) { 1978 * // Must be in the synchronized block 1979 * Iterator<E> it = set.iterator(); 1980 * while (it.hasNext()) { 1981 * foo(it.next()); 1982 * } 1983 * } 1984 * }</pre> 1985 * 1986 * <p>or: 1987 * 1988 * <pre>{@code 1989 * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); 1990 * NavigableSet<E> set2 = set.descendingSet().headSet(foo); 1991 * ... 1992 * synchronized (set) { // Note: set, not set2!!! 1993 * // Must be in the synchronized block 1994 * Iterator<E> it = set2.descendingIterator(); 1995 * while (it.hasNext()) 1996 * foo(it.next()); 1997 * } 1998 * } 1999 * }</pre> 2000 * 2001 * <p>Failure to follow this advice may result in non-deterministic behavior. 2002 * 2003 * <p>The returned navigable set will be serializable if the specified navigable set is 2004 * serializable. 2005 * 2006 * <p><b>Java 8+ users and later:</b> Prefer {@link Collections#synchronizedNavigableSet}. 2007 * 2008 * @param navigableSet the navigable set to be "wrapped" in a synchronized navigable set. 2009 * @return a synchronized view of the specified navigable set. 2010 * @since 13.0 2011 */ 2012 @GwtIncompatible // NavigableSet 2013 @J2ktIncompatible // Synchronized 2014 public static <E extends @Nullable Object> NavigableSet<E> synchronizedNavigableSet( 2015 NavigableSet<E> navigableSet) { 2016 return Synchronized.navigableSet(navigableSet); 2017 } 2018 2019 /** Remove each element in an iterable from a set. */ 2020 static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) { 2021 boolean changed = false; 2022 while (iterator.hasNext()) { 2023 changed |= set.remove(iterator.next()); 2024 } 2025 return changed; 2026 } 2027 2028 static boolean removeAllImpl(Set<?> set, Collection<?> collection) { 2029 checkNotNull(collection); // for GWT 2030 if (collection instanceof Multiset) { 2031 collection = ((Multiset<?>) collection).elementSet(); 2032 } 2033 /* 2034 * AbstractSet.removeAll(List) has quadratic behavior if the list size 2035 * is just more than the set's size. We augment the test by 2036 * assuming that sets have fast contains() performance, and other 2037 * collections don't. See 2038 * http://code.google.com/p/guava-libraries/issues/detail?id=1013 2039 */ 2040 if (collection instanceof Set && collection.size() > set.size()) { 2041 return Iterators.removeAll(set.iterator(), collection); 2042 } else { 2043 return removeAllImpl(set, collection.iterator()); 2044 } 2045 } 2046 2047 @GwtIncompatible // NavigableSet 2048 static class DescendingSet<E extends @Nullable Object> extends ForwardingNavigableSet<E> { 2049 private final NavigableSet<E> forward; 2050 2051 DescendingSet(NavigableSet<E> forward) { 2052 this.forward = forward; 2053 } 2054 2055 @Override 2056 protected NavigableSet<E> delegate() { 2057 return forward; 2058 } 2059 2060 @Override 2061 @CheckForNull 2062 public E lower(@ParametricNullness E e) { 2063 return forward.higher(e); 2064 } 2065 2066 @Override 2067 @CheckForNull 2068 public E floor(@ParametricNullness E e) { 2069 return forward.ceiling(e); 2070 } 2071 2072 @Override 2073 @CheckForNull 2074 public E ceiling(@ParametricNullness E e) { 2075 return forward.floor(e); 2076 } 2077 2078 @Override 2079 @CheckForNull 2080 public E higher(@ParametricNullness E e) { 2081 return forward.lower(e); 2082 } 2083 2084 @Override 2085 @CheckForNull 2086 public E pollFirst() { 2087 return forward.pollLast(); 2088 } 2089 2090 @Override 2091 @CheckForNull 2092 public E pollLast() { 2093 return forward.pollFirst(); 2094 } 2095 2096 @Override 2097 public NavigableSet<E> descendingSet() { 2098 return forward; 2099 } 2100 2101 @Override 2102 public Iterator<E> descendingIterator() { 2103 return forward.iterator(); 2104 } 2105 2106 @Override 2107 public NavigableSet<E> subSet( 2108 @ParametricNullness E fromElement, 2109 boolean fromInclusive, 2110 @ParametricNullness E toElement, 2111 boolean toInclusive) { 2112 return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); 2113 } 2114 2115 @Override 2116 public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) { 2117 return standardSubSet(fromElement, toElement); 2118 } 2119 2120 @Override 2121 public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) { 2122 return forward.tailSet(toElement, inclusive).descendingSet(); 2123 } 2124 2125 @Override 2126 public SortedSet<E> headSet(@ParametricNullness E toElement) { 2127 return standardHeadSet(toElement); 2128 } 2129 2130 @Override 2131 public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) { 2132 return forward.headSet(fromElement, inclusive).descendingSet(); 2133 } 2134 2135 @Override 2136 public SortedSet<E> tailSet(@ParametricNullness E fromElement) { 2137 return standardTailSet(fromElement); 2138 } 2139 2140 @SuppressWarnings("unchecked") 2141 @Override 2142 public Comparator<? super E> comparator() { 2143 Comparator<? super E> forwardComparator = forward.comparator(); 2144 if (forwardComparator == null) { 2145 return (Comparator) Ordering.natural().reverse(); 2146 } else { 2147 return reverse(forwardComparator); 2148 } 2149 } 2150 2151 // If we inline this, we get a javac error. 2152 private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) { 2153 return Ordering.from(forward).reverse(); 2154 } 2155 2156 @Override 2157 @ParametricNullness 2158 public E first() { 2159 return forward.last(); 2160 } 2161 2162 @Override 2163 @ParametricNullness 2164 public E last() { 2165 return forward.first(); 2166 } 2167 2168 @Override 2169 public Iterator<E> iterator() { 2170 return forward.descendingIterator(); 2171 } 2172 2173 @Override 2174 public @Nullable Object[] toArray() { 2175 return standardToArray(); 2176 } 2177 2178 @Override 2179 @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations 2180 public <T extends @Nullable Object> T[] toArray(T[] array) { 2181 return standardToArray(array); 2182 } 2183 2184 @Override 2185 public String toString() { 2186 return standardToString(); 2187 } 2188 } 2189 2190 /** 2191 * Returns a view of the portion of {@code set} whose elements are contained by {@code range}. 2192 * 2193 * <p>This method delegates to the appropriate methods of {@link NavigableSet} (namely {@link 2194 * NavigableSet#subSet(Object, boolean, Object, boolean) subSet()}, {@link 2195 * NavigableSet#tailSet(Object, boolean) tailSet()}, and {@link NavigableSet#headSet(Object, 2196 * boolean) headSet()}) to actually construct the view. Consult these methods for a full 2197 * description of the returned view's behavior. 2198 * 2199 * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural 2200 * ordering. {@code NavigableSet} on the other hand can specify a custom ordering via a {@link 2201 * Comparator}, which can violate the natural ordering. Using this method (or in general using 2202 * {@code Range}) with unnaturally-ordered sets can lead to unexpected and undefined behavior. 2203 * 2204 * @since 20.0 2205 */ 2206 @GwtIncompatible // NavigableSet 2207 public static <K extends Comparable<? super K>> NavigableSet<K> subSet( 2208 NavigableSet<K> set, Range<K> range) { 2209 if (set.comparator() != null 2210 && set.comparator() != Ordering.natural() 2211 && range.hasLowerBound() 2212 && range.hasUpperBound()) { 2213 checkArgument( 2214 set.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0, 2215 "set is using a custom comparator which is inconsistent with the natural ordering."); 2216 } 2217 if (range.hasLowerBound() && range.hasUpperBound()) { 2218 return set.subSet( 2219 range.lowerEndpoint(), 2220 range.lowerBoundType() == BoundType.CLOSED, 2221 range.upperEndpoint(), 2222 range.upperBoundType() == BoundType.CLOSED); 2223 } else if (range.hasLowerBound()) { 2224 return set.tailSet(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED); 2225 } else if (range.hasUpperBound()) { 2226 return set.headSet(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); 2227 } 2228 return checkNotNull(set); 2229 } 2230}