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