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