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