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 * Returns a new hash set using the smallest initial table size that can hold {@code expectedSize} 188 * elements without resizing. Note that this is not what {@link HashSet#HashSet(int)} does, but it 189 * is what most users want and expect it to do. 190 * 191 * <p>This behavior can't be broadly guaranteed, but has been tested with OpenJDK 1.7 and 1.8. 192 * 193 * @param expectedSize the number of elements you expect to add to the returned set 194 * @return a new, empty hash set with enough capacity to hold {@code expectedSize} elements 195 * without resizing 196 * @throws IllegalArgumentException if {@code expectedSize} is negative 197 */ 198 public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) { 199 return new HashSet<E>(Maps.capacity(expectedSize)); 200 } 201 202 /** 203 * Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin 204 * convenience for creating an empty set then calling {@link Collection#addAll} or {@link 205 * Iterables#addAll}. 206 * 207 * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link 208 * ImmutableSet#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link 209 * FluentIterable} and call {@code elements.toSet()}.) 210 * 211 * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link #newEnumSet(Iterable, Class)} 212 * instead. 213 * 214 * <p><b>Note for Java 7 and later:</b> if {@code elements} is a {@link Collection}, you don't 215 * need this method. Instead, use the {@code HashSet} constructor directly, taking advantage of 216 * the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. 217 * 218 * <p>Overall, this method is not very useful and will likely be deprecated in the future. 219 */ 220 public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) { 221 return (elements instanceof Collection) 222 ? new HashSet<E>(Collections2.cast(elements)) 223 : newHashSet(elements.iterator()); 224 } 225 226 /** 227 * Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin 228 * convenience for creating an empty set and then calling {@link Iterators#addAll}. 229 * 230 * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link 231 * ImmutableSet#copyOf(Iterator)} instead. 232 * 233 * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an {@link EnumSet} 234 * instead. 235 * 236 * <p>Overall, this method is not very useful and will likely be deprecated in the future. 237 */ 238 public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) { 239 HashSet<E> set = newHashSet(); 240 Iterators.addAll(set, elements); 241 return set; 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 {@code LinkedHashSet} instance, with a high enough "initial capacity" that it 296 * <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be 297 * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed 298 * that the method isn't inadvertently <i>oversizing</i> the returned set. 299 * 300 * @param expectedSize the number of elements you expect to add to the returned set 301 * @return a new, empty {@code LinkedHashSet} with enough capacity to hold {@code expectedSize} 302 * elements without resizing 303 * @throws IllegalArgumentException if {@code expectedSize} is negative 304 * @since 11.0 305 */ 306 public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(int expectedSize) { 307 return new LinkedHashSet<E>(Maps.capacity(expectedSize)); 308 } 309 310 /** 311 * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the given elements in order. 312 * 313 * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link 314 * ImmutableSet#copyOf(Iterable)} instead. 315 * 316 * <p><b>Note for Java 7 and later:</b> if {@code elements} is a {@link Collection}, you don't 317 * need this method. Instead, use the {@code LinkedHashSet} constructor directly, taking advantage 318 * of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. 319 * 320 * <p>Overall, this method is not very useful and will likely be deprecated in the future. 321 * 322 * @param elements the elements that the set should contain, in order 323 * @return a new {@code LinkedHashSet} containing those elements (minus duplicates) 324 */ 325 public static <E> LinkedHashSet<E> newLinkedHashSet(Iterable<? extends E> elements) { 326 if (elements instanceof Collection) { 327 return new LinkedHashSet<E>(Collections2.cast(elements)); 328 } 329 LinkedHashSet<E> set = newLinkedHashSet(); 330 Iterables.addAll(set, elements); 331 return set; 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 ? Collections2.cast(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(set1, set2); 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 private static class FilteredSet<E> extends FilteredCollection<E> implements Set<E> { 969 FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) { 970 super(unfiltered, predicate); 971 } 972 973 @Override 974 public boolean equals(@NullableDecl Object object) { 975 return equalsImpl(this, object); 976 } 977 978 @Override 979 public int hashCode() { 980 return hashCodeImpl(this); 981 } 982 } 983 984 /** 985 * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that satisfy a predicate. The 986 * returned set is a live view of {@code unfiltered}; changes to one affect the other. 987 * 988 * <p>The resulting set's iterator does not support {@code remove()}, but all other set methods 989 * are supported. When given an element that doesn't satisfy the predicate, the set's {@code 990 * add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods 991 * such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements 992 * that satisfy the filter will be removed from the underlying set. 993 * 994 * <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is. 995 * 996 * <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in 997 * the underlying set and determine which elements satisfy the filter. When a live view is 998 * <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and 999 * use the copy. 1000 * 1001 * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at 1002 * {@link Predicate#apply}. Do not provide a predicate such as {@code 1003 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link 1004 * Iterables#filter(Iterable, Class)} for related functionality.) 1005 * 1006 * @since 11.0 1007 */ 1008 public static <E> SortedSet<E> filter(SortedSet<E> unfiltered, Predicate<? super E> predicate) { 1009 if (unfiltered instanceof FilteredSet) { 1010 // Support clear(), removeAll(), and retainAll() when filtering a filtered 1011 // collection. 1012 FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; 1013 Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); 1014 return new FilteredSortedSet<E>((SortedSet<E>) filtered.unfiltered, combinedPredicate); 1015 } 1016 1017 return new FilteredSortedSet<E>(checkNotNull(unfiltered), checkNotNull(predicate)); 1018 } 1019 1020 private static class FilteredSortedSet<E> extends FilteredSet<E> implements SortedSet<E> { 1021 1022 FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) { 1023 super(unfiltered, predicate); 1024 } 1025 1026 @Override 1027 public Comparator<? super E> comparator() { 1028 return ((SortedSet<E>) unfiltered).comparator(); 1029 } 1030 1031 @Override 1032 public SortedSet<E> subSet(E fromElement, E toElement) { 1033 return new FilteredSortedSet<E>( 1034 ((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate); 1035 } 1036 1037 @Override 1038 public SortedSet<E> headSet(E toElement) { 1039 return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate); 1040 } 1041 1042 @Override 1043 public SortedSet<E> tailSet(E fromElement) { 1044 return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate); 1045 } 1046 1047 @Override 1048 public E first() { 1049 return Iterators.find(unfiltered.iterator(), predicate); 1050 } 1051 1052 @Override 1053 public E last() { 1054 SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered; 1055 while (true) { 1056 E element = sortedUnfiltered.last(); 1057 if (predicate.apply(element)) { 1058 return element; 1059 } 1060 sortedUnfiltered = sortedUnfiltered.headSet(element); 1061 } 1062 } 1063 } 1064 1065 /** 1066 * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that satisfy a predicate. 1067 * The returned set is a live view of {@code unfiltered}; changes to one affect the other. 1068 * 1069 * <p>The resulting set's iterator does not support {@code remove()}, but all other set methods 1070 * are supported. When given an element that doesn't satisfy the predicate, the set's {@code 1071 * add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods 1072 * such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements 1073 * that satisfy the filter will be removed from the underlying set. 1074 * 1075 * <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is. 1076 * 1077 * <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in 1078 * the underlying set and determine which elements satisfy the filter. When a live view is 1079 * <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and 1080 * use the copy. 1081 * 1082 * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at 1083 * {@link Predicate#apply}. Do not provide a predicate such as {@code 1084 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link 1085 * Iterables#filter(Iterable, Class)} for related functionality.) 1086 * 1087 * @since 14.0 1088 */ 1089 @GwtIncompatible // NavigableSet 1090 @SuppressWarnings("unchecked") 1091 public static <E> NavigableSet<E> filter( 1092 NavigableSet<E> unfiltered, Predicate<? super E> predicate) { 1093 if (unfiltered instanceof FilteredSet) { 1094 // Support clear(), removeAll(), and retainAll() when filtering a filtered 1095 // collection. 1096 FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; 1097 Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); 1098 return new FilteredNavigableSet<E>((NavigableSet<E>) filtered.unfiltered, combinedPredicate); 1099 } 1100 1101 return new FilteredNavigableSet<E>(checkNotNull(unfiltered), checkNotNull(predicate)); 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 * @since 2.0 1231 */ 1232 public static <B> Set<List<B>> cartesianProduct(List<? extends Set<? extends B>> sets) { 1233 return CartesianSet.create(sets); 1234 } 1235 1236 /** 1237 * Returns every possible list that can be formed by choosing one element from each of the given 1238 * sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian 1239 * product</a>" of the sets. For example: 1240 * 1241 * <pre>{@code 1242 * Sets.cartesianProduct( 1243 * ImmutableSet.of(1, 2), 1244 * ImmutableSet.of("A", "B", "C")) 1245 * }</pre> 1246 * 1247 * <p>returns a set containing six lists: 1248 * 1249 * <ul> 1250 * <li>{@code ImmutableList.of(1, "A")} 1251 * <li>{@code ImmutableList.of(1, "B")} 1252 * <li>{@code ImmutableList.of(1, "C")} 1253 * <li>{@code ImmutableList.of(2, "A")} 1254 * <li>{@code ImmutableList.of(2, "B")} 1255 * <li>{@code ImmutableList.of(2, "C")} 1256 * </ul> 1257 * 1258 * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian 1259 * products that you would get from nesting for loops: 1260 * 1261 * <pre>{@code 1262 * for (B b0 : sets.get(0)) { 1263 * for (B b1 : sets.get(1)) { 1264 * ... 1265 * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); 1266 * // operate on tuple 1267 * } 1268 * } 1269 * }</pre> 1270 * 1271 * <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at 1272 * all are provided (an empty list), the resulting Cartesian product has one element, an empty 1273 * list (counter-intuitive, but mathematically consistent). 1274 * 1275 * <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a 1276 * set of size {@code m x n x p}, its actual memory consumption is much smaller. When the 1277 * cartesian set is constructed, the input sets are merely copied. Only as the resulting set is 1278 * iterated are the individual lists created, and these are not retained after iteration. 1279 * 1280 * @param sets the sets to choose elements from, in the order that the elements chosen from those 1281 * sets should appear in the resulting lists 1282 * @param <B> any common base class shared by all axes (often just {@link Object}) 1283 * @return the Cartesian product, as an immutable set containing immutable lists 1284 * @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a 1285 * provided set is null 1286 * @since 2.0 1287 */ 1288 public static <B> Set<List<B>> cartesianProduct(Set<? extends B>... sets) { 1289 return cartesianProduct(Arrays.asList(sets)); 1290 } 1291 1292 private static final class CartesianSet<E> extends ForwardingCollection<List<E>> 1293 implements Set<List<E>> { 1294 private final transient ImmutableList<ImmutableSet<E>> axes; 1295 private final transient CartesianList<E> delegate; 1296 1297 static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) { 1298 ImmutableList.Builder<ImmutableSet<E>> axesBuilder = new ImmutableList.Builder<>(sets.size()); 1299 for (Set<? extends E> set : sets) { 1300 ImmutableSet<E> copy = ImmutableSet.copyOf(set); 1301 if (copy.isEmpty()) { 1302 return ImmutableSet.of(); 1303 } 1304 axesBuilder.add(copy); 1305 } 1306 final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build(); 1307 ImmutableList<List<E>> listAxes = 1308 new ImmutableList<List<E>>() { 1309 @Override 1310 public int size() { 1311 return axes.size(); 1312 } 1313 1314 @Override 1315 public List<E> get(int index) { 1316 return axes.get(index).asList(); 1317 } 1318 1319 @Override 1320 boolean isPartialView() { 1321 return true; 1322 } 1323 }; 1324 return new CartesianSet<E>(axes, new CartesianList<E>(listAxes)); 1325 } 1326 1327 private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) { 1328 this.axes = axes; 1329 this.delegate = delegate; 1330 } 1331 1332 @Override 1333 protected Collection<List<E>> delegate() { 1334 return delegate; 1335 } 1336 1337 @Override 1338 public boolean equals(@NullableDecl Object object) { 1339 // Warning: this is broken if size() == 0, so it is critical that we 1340 // substitute an empty ImmutableSet to the user in place of this 1341 if (object instanceof CartesianSet) { 1342 CartesianSet<?> that = (CartesianSet<?>) object; 1343 return this.axes.equals(that.axes); 1344 } 1345 return super.equals(object); 1346 } 1347 1348 @Override 1349 public int hashCode() { 1350 // Warning: this is broken if size() == 0, so it is critical that we 1351 // substitute an empty ImmutableSet to the user in place of this 1352 1353 // It's a weird formula, but tests prove it works. 1354 int adjust = size() - 1; 1355 for (int i = 0; i < axes.size(); i++) { 1356 adjust *= 31; 1357 adjust = ~~adjust; 1358 // in GWT, we have to deal with integer overflow carefully 1359 } 1360 int hash = 1; 1361 for (Set<E> axis : axes) { 1362 hash = 31 * hash + (size() / axis.size() * axis.hashCode()); 1363 1364 hash = ~~hash; 1365 } 1366 hash += adjust; 1367 return ~~hash; 1368 } 1369 } 1370 1371 /** 1372 * Returns the set of all possible subsets of {@code set}. For example, {@code 1373 * powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, {1}, {2}, {1, 2}}}. 1374 * 1375 * <p>Elements appear in these subsets in the same iteration order as they appeared in the input 1376 * set. The order in which these subsets appear in the outer set is undefined. Note that the power 1377 * set of the empty set is not the empty set, but a one-element set containing the empty set. 1378 * 1379 * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements 1380 * are identical, even if the input set uses a different concept of equivalence. 1381 * 1382 * <p><i>Performance notes:</i> while the power set of a set with size {@code n} is of size {@code 1383 * 2^n}, its memory usage is only {@code O(n)}. When the power set is constructed, the input set 1384 * is merely copied. Only as the power set is iterated are the individual subsets created, and 1385 * these subsets themselves occupy only a small constant amount of memory. 1386 * 1387 * @param set the set of elements to construct a power set from 1388 * @return the power set, as an immutable set of immutable sets 1389 * @throws IllegalArgumentException if {@code set} has more than 30 unique elements (causing the 1390 * power set size to exceed the {@code int} range) 1391 * @throws NullPointerException if {@code set} is or contains {@code null} 1392 * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at Wikipedia</a> 1393 * @since 4.0 1394 */ 1395 @GwtCompatible(serializable = false) 1396 public static <E> Set<Set<E>> powerSet(Set<E> set) { 1397 return new PowerSet<E>(set); 1398 } 1399 1400 private static final class SubSet<E> extends AbstractSet<E> { 1401 private final ImmutableMap<E, Integer> inputSet; 1402 private final int mask; 1403 1404 SubSet(ImmutableMap<E, Integer> inputSet, int mask) { 1405 this.inputSet = inputSet; 1406 this.mask = mask; 1407 } 1408 1409 @Override 1410 public Iterator<E> iterator() { 1411 return new UnmodifiableIterator<E>() { 1412 final ImmutableList<E> elements = inputSet.keySet().asList(); 1413 int remainingSetBits = mask; 1414 1415 @Override 1416 public boolean hasNext() { 1417 return remainingSetBits != 0; 1418 } 1419 1420 @Override 1421 public E next() { 1422 int index = Integer.numberOfTrailingZeros(remainingSetBits); 1423 if (index == 32) { 1424 throw new NoSuchElementException(); 1425 } 1426 remainingSetBits &= ~(1 << index); 1427 return elements.get(index); 1428 } 1429 }; 1430 } 1431 1432 @Override 1433 public int size() { 1434 return Integer.bitCount(mask); 1435 } 1436 1437 @Override 1438 public boolean contains(@NullableDecl Object o) { 1439 Integer index = inputSet.get(o); 1440 return index != null && (mask & (1 << index)) != 0; 1441 } 1442 } 1443 1444 private static final class PowerSet<E> extends AbstractSet<Set<E>> { 1445 final ImmutableMap<E, Integer> inputSet; 1446 1447 PowerSet(Set<E> input) { 1448 this.inputSet = Maps.indexMap(input); 1449 checkArgument( 1450 inputSet.size() <= 30, "Too many elements to create power set: %s > 30", inputSet.size()); 1451 } 1452 1453 @Override 1454 public int size() { 1455 return 1 << inputSet.size(); 1456 } 1457 1458 @Override 1459 public boolean isEmpty() { 1460 return false; 1461 } 1462 1463 @Override 1464 public Iterator<Set<E>> iterator() { 1465 return new AbstractIndexedListIterator<Set<E>>(size()) { 1466 @Override 1467 protected Set<E> get(final int setBits) { 1468 return new SubSet<E>(inputSet, setBits); 1469 } 1470 }; 1471 } 1472 1473 @Override 1474 public boolean contains(@NullableDecl Object obj) { 1475 if (obj instanceof Set) { 1476 Set<?> set = (Set<?>) obj; 1477 return inputSet.keySet().containsAll(set); 1478 } 1479 return false; 1480 } 1481 1482 @Override 1483 public boolean equals(@NullableDecl Object obj) { 1484 if (obj instanceof PowerSet) { 1485 PowerSet<?> that = (PowerSet<?>) obj; 1486 return inputSet.equals(that.inputSet); 1487 } 1488 return super.equals(obj); 1489 } 1490 1491 @Override 1492 public int hashCode() { 1493 /* 1494 * The sum of the sums of the hash codes in each subset is just the sum of 1495 * each input element's hash code times the number of sets that element 1496 * appears in. Each element appears in exactly half of the 2^n sets, so: 1497 */ 1498 return inputSet.keySet().hashCode() << (inputSet.size() - 1); 1499 } 1500 1501 @Override 1502 public String toString() { 1503 return "powerSet(" + inputSet + ")"; 1504 } 1505 } 1506 1507 /** 1508 * Returns the set of all subsets of {@code set} of size {@code size}. For example, {@code 1509 * combinations(ImmutableSet.of(1, 2, 3), 2)} returns the set {@code {{1, 2}, {1, 3}, {2, 3}}}. 1510 * 1511 * <p>Elements appear in these subsets in the same iteration order as they appeared in the input 1512 * set. The order in which these subsets appear in the outer set is undefined. 1513 * 1514 * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements 1515 * are identical, even if the input set uses a different concept of equivalence. 1516 * 1517 * <p><i>Performance notes:</i> the memory usage of the returned set is only {@code O(n)}. When 1518 * the result set is constructed, the input set is merely copied. Only as the result set is 1519 * iterated are the individual subsets created. Each of these subsets occupies an additional O(n) 1520 * memory but only for as long as the user retains a reference to it. That is, the set returned by 1521 * {@code combinations} does not retain the individual subsets. 1522 * 1523 * @param set the set of elements to take combinations of 1524 * @param size the number of elements per combination 1525 * @return the set of all combinations of {@code size} elements from {@code set} 1526 * @throws IllegalArgumentException if {@code size} is not between 0 and {@code set.size()} 1527 * inclusive 1528 * @throws NullPointerException if {@code set} is or contains {@code null} 1529 * @since 23.0 1530 */ 1531 @Beta 1532 public static <E> Set<Set<E>> combinations(Set<E> set, final int size) { 1533 final ImmutableMap<E, Integer> index = Maps.indexMap(set); 1534 checkNonnegative(size, "size"); 1535 checkArgument(size <= index.size(), "size (%s) must be <= set.size() (%s)", size, index.size()); 1536 if (size == 0) { 1537 return ImmutableSet.<Set<E>>of(ImmutableSet.<E>of()); 1538 } else if (size == index.size()) { 1539 return ImmutableSet.<Set<E>>of(index.keySet()); 1540 } 1541 return new AbstractSet<Set<E>>() { 1542 @Override 1543 public boolean contains(@NullableDecl Object o) { 1544 if (o instanceof Set) { 1545 Set<?> s = (Set<?>) o; 1546 return s.size() == size && index.keySet().containsAll(s); 1547 } 1548 return false; 1549 } 1550 1551 @Override 1552 public Iterator<Set<E>> iterator() { 1553 return new AbstractIterator<Set<E>>() { 1554 final BitSet bits = new BitSet(index.size()); 1555 1556 @Override 1557 protected Set<E> computeNext() { 1558 if (bits.isEmpty()) { 1559 bits.set(0, size); 1560 } else { 1561 int firstSetBit = bits.nextSetBit(0); 1562 int bitToFlip = bits.nextClearBit(firstSetBit); 1563 1564 if (bitToFlip == index.size()) { 1565 return endOfData(); 1566 } 1567 /* 1568 * The current set in sorted order looks like 1569 * {firstSetBit, firstSetBit + 1, ..., bitToFlip - 1, ...} 1570 * where it does *not* contain bitToFlip. 1571 * 1572 * The next combination is 1573 * 1574 * {0, 1, ..., bitToFlip - firstSetBit - 2, bitToFlip, ...} 1575 * 1576 * This is lexicographically next if you look at the combinations in descending order 1577 * e.g. {2, 1, 0}, {3, 1, 0}, {3, 2, 0}, {3, 2, 1}, {4, 1, 0}... 1578 */ 1579 1580 bits.set(0, bitToFlip - firstSetBit - 1); 1581 bits.clear(bitToFlip - firstSetBit - 1, bitToFlip); 1582 bits.set(bitToFlip); 1583 } 1584 final BitSet copy = (BitSet) bits.clone(); 1585 return new AbstractSet<E>() { 1586 @Override 1587 public boolean contains(@NullableDecl Object o) { 1588 Integer i = index.get(o); 1589 return i != null && copy.get(i); 1590 } 1591 1592 @Override 1593 public Iterator<E> iterator() { 1594 return new AbstractIterator<E>() { 1595 int i = -1; 1596 1597 @Override 1598 protected E computeNext() { 1599 i = copy.nextSetBit(i + 1); 1600 if (i == -1) { 1601 return endOfData(); 1602 } 1603 return index.keySet().asList().get(i); 1604 } 1605 }; 1606 } 1607 1608 @Override 1609 public int size() { 1610 return size; 1611 } 1612 }; 1613 } 1614 }; 1615 } 1616 1617 @Override 1618 public int size() { 1619 return IntMath.binomial(index.size(), size); 1620 } 1621 1622 @Override 1623 public String toString() { 1624 return "Sets.combinations(" + index.keySet() + ", " + size + ")"; 1625 } 1626 }; 1627 } 1628 1629 /** An implementation for {@link Set#hashCode()}. */ 1630 static int hashCodeImpl(Set<?> s) { 1631 int hashCode = 0; 1632 for (Object o : s) { 1633 hashCode += o != null ? o.hashCode() : 0; 1634 1635 hashCode = ~~hashCode; 1636 // Needed to deal with unusual integer overflow in GWT. 1637 } 1638 return hashCode; 1639 } 1640 1641 /** An implementation for {@link Set#equals(Object)}. */ 1642 static boolean equalsImpl(Set<?> s, @NullableDecl Object object) { 1643 if (s == object) { 1644 return true; 1645 } 1646 if (object instanceof Set) { 1647 Set<?> o = (Set<?>) object; 1648 1649 try { 1650 return s.size() == o.size() && s.containsAll(o); 1651 } catch (NullPointerException | ClassCastException ignored) { 1652 return false; 1653 } 1654 } 1655 return false; 1656 } 1657 1658 /** 1659 * Returns an unmodifiable view of the specified navigable set. This method allows modules to 1660 * provide users with "read-only" access to internal navigable sets. Query operations on the 1661 * returned set "read through" to the specified set, and attempts to modify the returned set, 1662 * whether direct or via its collection views, result in an {@code UnsupportedOperationException}. 1663 * 1664 * <p>The returned navigable set will be serializable if the specified navigable set is 1665 * serializable. 1666 * 1667 * @param set the navigable set for which an unmodifiable view is to be returned 1668 * @return an unmodifiable view of the specified navigable set 1669 * @since 12.0 1670 */ 1671 public static <E> NavigableSet<E> unmodifiableNavigableSet(NavigableSet<E> set) { 1672 if (set instanceof ImmutableCollection || set instanceof UnmodifiableNavigableSet) { 1673 return set; 1674 } 1675 return new UnmodifiableNavigableSet<E>(set); 1676 } 1677 1678 static final class UnmodifiableNavigableSet<E> extends ForwardingSortedSet<E> 1679 implements NavigableSet<E>, Serializable { 1680 private final NavigableSet<E> delegate; 1681 private final SortedSet<E> unmodifiableDelegate; 1682 1683 UnmodifiableNavigableSet(NavigableSet<E> delegate) { 1684 this.delegate = checkNotNull(delegate); 1685 this.unmodifiableDelegate = Collections.unmodifiableSortedSet(delegate); 1686 } 1687 1688 @Override 1689 protected SortedSet<E> delegate() { 1690 return unmodifiableDelegate; 1691 } 1692 1693 @Override 1694 public E lower(E e) { 1695 return delegate.lower(e); 1696 } 1697 1698 @Override 1699 public E floor(E e) { 1700 return delegate.floor(e); 1701 } 1702 1703 @Override 1704 public E ceiling(E e) { 1705 return delegate.ceiling(e); 1706 } 1707 1708 @Override 1709 public E higher(E e) { 1710 return delegate.higher(e); 1711 } 1712 1713 @Override 1714 public E pollFirst() { 1715 throw new UnsupportedOperationException(); 1716 } 1717 1718 @Override 1719 public E pollLast() { 1720 throw new UnsupportedOperationException(); 1721 } 1722 1723 private transient UnmodifiableNavigableSet<E> descendingSet; 1724 1725 @Override 1726 public NavigableSet<E> descendingSet() { 1727 UnmodifiableNavigableSet<E> result = descendingSet; 1728 if (result == null) { 1729 result = descendingSet = new UnmodifiableNavigableSet<E>(delegate.descendingSet()); 1730 result.descendingSet = this; 1731 } 1732 return result; 1733 } 1734 1735 @Override 1736 public Iterator<E> descendingIterator() { 1737 return Iterators.unmodifiableIterator(delegate.descendingIterator()); 1738 } 1739 1740 @Override 1741 public NavigableSet<E> subSet( 1742 E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { 1743 return unmodifiableNavigableSet( 1744 delegate.subSet(fromElement, fromInclusive, toElement, toInclusive)); 1745 } 1746 1747 @Override 1748 public NavigableSet<E> headSet(E toElement, boolean inclusive) { 1749 return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive)); 1750 } 1751 1752 @Override 1753 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { 1754 return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive)); 1755 } 1756 1757 private static final long serialVersionUID = 0; 1758 } 1759 1760 /** 1761 * Returns a synchronized (thread-safe) navigable set backed by the specified navigable set. In 1762 * order to guarantee serial access, it is critical that <b>all</b> access to the backing 1763 * navigable set is accomplished through the returned navigable set (or its views). 1764 * 1765 * <p>It is imperative that the user manually synchronize on the returned sorted set when 1766 * iterating over it or any of its {@code descendingSet}, {@code subSet}, {@code headSet}, or 1767 * {@code tailSet} views. 1768 * 1769 * <pre>{@code 1770 * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); 1771 * ... 1772 * synchronized (set) { 1773 * // Must be in the synchronized block 1774 * Iterator<E> it = set.iterator(); 1775 * while (it.hasNext()) { 1776 * foo(it.next()); 1777 * } 1778 * } 1779 * }</pre> 1780 * 1781 * <p>or: 1782 * 1783 * <pre>{@code 1784 * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); 1785 * NavigableSet<E> set2 = set.descendingSet().headSet(foo); 1786 * ... 1787 * synchronized (set) { // Note: set, not set2!!! 1788 * // Must be in the synchronized block 1789 * Iterator<E> it = set2.descendingIterator(); 1790 * while (it.hasNext()) 1791 * foo(it.next()); 1792 * } 1793 * } 1794 * }</pre> 1795 * 1796 * <p>Failure to follow this advice may result in non-deterministic behavior. 1797 * 1798 * <p>The returned navigable set will be serializable if the specified navigable set is 1799 * serializable. 1800 * 1801 * @param navigableSet the navigable set to be "wrapped" in a synchronized navigable set. 1802 * @return a synchronized view of the specified navigable set. 1803 * @since 13.0 1804 */ 1805 @GwtIncompatible // NavigableSet 1806 public static <E> NavigableSet<E> synchronizedNavigableSet(NavigableSet<E> navigableSet) { 1807 return Synchronized.navigableSet(navigableSet); 1808 } 1809 1810 /** Remove each element in an iterable from a set. */ 1811 static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) { 1812 boolean changed = false; 1813 while (iterator.hasNext()) { 1814 changed |= set.remove(iterator.next()); 1815 } 1816 return changed; 1817 } 1818 1819 static boolean removeAllImpl(Set<?> set, Collection<?> collection) { 1820 checkNotNull(collection); // for GWT 1821 if (collection instanceof Multiset) { 1822 collection = ((Multiset<?>) collection).elementSet(); 1823 } 1824 /* 1825 * AbstractSet.removeAll(List) has quadratic behavior if the list size 1826 * is just more than the set's size. We augment the test by 1827 * assuming that sets have fast contains() performance, and other 1828 * collections don't. See 1829 * http://code.google.com/p/guava-libraries/issues/detail?id=1013 1830 */ 1831 if (collection instanceof Set && collection.size() > set.size()) { 1832 return Iterators.removeAll(set.iterator(), collection); 1833 } else { 1834 return removeAllImpl(set, collection.iterator()); 1835 } 1836 } 1837 1838 @GwtIncompatible // NavigableSet 1839 static class DescendingSet<E> extends ForwardingNavigableSet<E> { 1840 private final NavigableSet<E> forward; 1841 1842 DescendingSet(NavigableSet<E> forward) { 1843 this.forward = forward; 1844 } 1845 1846 @Override 1847 protected NavigableSet<E> delegate() { 1848 return forward; 1849 } 1850 1851 @Override 1852 public E lower(E e) { 1853 return forward.higher(e); 1854 } 1855 1856 @Override 1857 public E floor(E e) { 1858 return forward.ceiling(e); 1859 } 1860 1861 @Override 1862 public E ceiling(E e) { 1863 return forward.floor(e); 1864 } 1865 1866 @Override 1867 public E higher(E e) { 1868 return forward.lower(e); 1869 } 1870 1871 @Override 1872 public E pollFirst() { 1873 return forward.pollLast(); 1874 } 1875 1876 @Override 1877 public E pollLast() { 1878 return forward.pollFirst(); 1879 } 1880 1881 @Override 1882 public NavigableSet<E> descendingSet() { 1883 return forward; 1884 } 1885 1886 @Override 1887 public Iterator<E> descendingIterator() { 1888 return forward.iterator(); 1889 } 1890 1891 @Override 1892 public NavigableSet<E> subSet( 1893 E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { 1894 return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); 1895 } 1896 1897 @Override 1898 public NavigableSet<E> headSet(E toElement, boolean inclusive) { 1899 return forward.tailSet(toElement, inclusive).descendingSet(); 1900 } 1901 1902 @Override 1903 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { 1904 return forward.headSet(fromElement, inclusive).descendingSet(); 1905 } 1906 1907 @SuppressWarnings("unchecked") 1908 @Override 1909 public Comparator<? super E> comparator() { 1910 Comparator<? super E> forwardComparator = forward.comparator(); 1911 if (forwardComparator == null) { 1912 return (Comparator) Ordering.natural().reverse(); 1913 } else { 1914 return reverse(forwardComparator); 1915 } 1916 } 1917 1918 // If we inline this, we get a javac error. 1919 private static <T> Ordering<T> reverse(Comparator<T> forward) { 1920 return Ordering.from(forward).reverse(); 1921 } 1922 1923 @Override 1924 public E first() { 1925 return forward.last(); 1926 } 1927 1928 @Override 1929 public SortedSet<E> headSet(E toElement) { 1930 return standardHeadSet(toElement); 1931 } 1932 1933 @Override 1934 public E last() { 1935 return forward.first(); 1936 } 1937 1938 @Override 1939 public SortedSet<E> subSet(E fromElement, E toElement) { 1940 return standardSubSet(fromElement, toElement); 1941 } 1942 1943 @Override 1944 public SortedSet<E> tailSet(E fromElement) { 1945 return standardTailSet(fromElement); 1946 } 1947 1948 @Override 1949 public Iterator<E> iterator() { 1950 return forward.descendingIterator(); 1951 } 1952 1953 @Override 1954 public Object[] toArray() { 1955 return standardToArray(); 1956 } 1957 1958 @Override 1959 public <T> T[] toArray(T[] array) { 1960 return standardToArray(array); 1961 } 1962 1963 @Override 1964 public String toString() { 1965 return standardToString(); 1966 } 1967 } 1968 1969 /** 1970 * Returns a view of the portion of {@code set} whose elements are contained by {@code range}. 1971 * 1972 * <p>This method delegates to the appropriate methods of {@link NavigableSet} (namely {@link 1973 * NavigableSet#subSet(Object, boolean, Object, boolean) subSet()}, {@link 1974 * NavigableSet#tailSet(Object, boolean) tailSet()}, and {@link NavigableSet#headSet(Object, 1975 * boolean) headSet()}) to actually construct the view. Consult these methods for a full 1976 * description of the returned view's behavior. 1977 * 1978 * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural 1979 * ordering. {@code NavigableSet} on the other hand can specify a custom ordering via a {@link 1980 * Comparator}, which can violate the natural ordering. Using this method (or in general using 1981 * {@code Range}) with unnaturally-ordered sets can lead to unexpected and undefined behavior. 1982 * 1983 * @since 20.0 1984 */ 1985 @Beta 1986 @GwtIncompatible // NavigableSet 1987 public static <K extends Comparable<? super K>> NavigableSet<K> subSet( 1988 NavigableSet<K> set, Range<K> range) { 1989 if (set.comparator() != null 1990 && set.comparator() != Ordering.natural() 1991 && range.hasLowerBound() 1992 && range.hasUpperBound()) { 1993 checkArgument( 1994 set.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0, 1995 "set is using a custom comparator which is inconsistent with the natural ordering."); 1996 } 1997 if (range.hasLowerBound() && range.hasUpperBound()) { 1998 return set.subSet( 1999 range.lowerEndpoint(), 2000 range.lowerBoundType() == BoundType.CLOSED, 2001 range.upperEndpoint(), 2002 range.upperBoundType() == BoundType.CLOSED); 2003 } else if (range.hasLowerBound()) { 2004 return set.tailSet(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED); 2005 } else if (range.hasUpperBound()) { 2006 return set.headSet(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); 2007 } 2008 return checkNotNull(set); 2009 } 2010}