Class Sets
- java.lang.Object
-
- com.google.common.collect.Sets
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classSets.SetView<E extends @Nullable java.lang.Object>An unmodifiable view of a set which may be backed by other sets; this view will change as the backing sets do.
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static <B> java.util.Set<java.util.List<B>>cartesianProduct(java.util.List<? extends java.util.Set<? extends B>> sets)Returns every possible list that can be formed by choosing one element from each of the given sets in order; the "n-ary Cartesian product" of the sets.static <B> java.util.Set<java.util.List<B>>cartesianProduct(java.util.Set<? extends B>... sets)Returns every possible list that can be formed by choosing one element from each of the given sets in order; the "n-ary Cartesian product" of the sets.static <E> java.util.Set<java.util.Set<E>>combinations(java.util.Set<E> set, int size)Returns the set of all subsets ofsetof sizesize.static <E extends java.lang.Enum<E>>
java.util.EnumSet<E>complementOf(java.util.Collection<E> collection)Creates anEnumSetconsisting of all enum values that are not in the specified collection.static <E extends java.lang.Enum<E>>
java.util.EnumSet<E>complementOf(java.util.Collection<E> collection, java.lang.Class<E> type)Creates anEnumSetconsisting of all enum values that are not in the specified collection.static <E extends @Nullable java.lang.Object>
Sets.SetView<E>difference(java.util.Set<E> set1, java.util.Set<?> set2)Returns an unmodifiable view of the difference of two sets.static <E extends @Nullable java.lang.Object>
java.util.NavigableSet<E>filter(java.util.NavigableSet<E> unfiltered, Predicate<? super E> predicate)Returns the elements of aNavigableSet,unfiltered, that satisfy a predicate.static <E extends @Nullable java.lang.Object>
java.util.Set<E>filter(java.util.Set<E> unfiltered, Predicate<? super E> predicate)Returns the elements ofunfilteredthat satisfy a predicate.static <E extends @Nullable java.lang.Object>
java.util.SortedSet<E>filter(java.util.SortedSet<E> unfiltered, Predicate<? super E> predicate)Returns the elements of aSortedSet,unfiltered, that satisfy a predicate.static <E extends java.lang.Enum<E>>
ImmutableSet<E>immutableEnumSet(E anElement, E... otherElements)Returns an immutable set instance containing the given enum elements.static <E extends java.lang.Enum<E>>
ImmutableSet<E>immutableEnumSet(java.lang.Iterable<E> elements)Returns an immutable set instance containing the given enum elements.static <E extends @Nullable java.lang.Object>
Sets.SetView<E>intersection(java.util.Set<E> set1, java.util.Set<?> set2)Returns an unmodifiable view of the intersection of two sets.static <E> java.util.Set<E>newConcurrentHashSet()Creates a thread-safe set backed by a hash map.static <E> java.util.Set<E>newConcurrentHashSet(java.lang.Iterable<? extends E> elements)Creates a thread-safe set backed by a hash map and containing the given elements.static <E extends @Nullable java.lang.Object>
java.util.concurrent.CopyOnWriteArraySet<E>newCopyOnWriteArraySet()Creates an emptyCopyOnWriteArraySetinstance.static <E extends @Nullable java.lang.Object>
java.util.concurrent.CopyOnWriteArraySet<E>newCopyOnWriteArraySet(java.lang.Iterable<? extends E> elements)Creates aCopyOnWriteArraySetinstance containing the given elements.static <E extends java.lang.Enum<E>>
java.util.EnumSet<E>newEnumSet(java.lang.Iterable<E> iterable, java.lang.Class<E> elementType)Returns a new, mutableEnumSetinstance containing the given elements in their natural order.static <E extends @Nullable java.lang.Object>
java.util.HashSet<E>newHashSet()Creates a mutable, initially emptyHashSetinstance.static <E extends @Nullable java.lang.Object>
java.util.HashSet<E>newHashSet(E... elements)Creates a mutableHashSetinstance initially containing the given elements.static <E extends @Nullable java.lang.Object>
java.util.HashSet<E>newHashSet(java.lang.Iterable<? extends E> elements)Creates a mutableHashSetinstance containing the given elements.static <E extends @Nullable java.lang.Object>
java.util.HashSet<E>newHashSet(java.util.Iterator<? extends E> elements)Creates a mutableHashSetinstance containing the given elements.static <E extends @Nullable java.lang.Object>
java.util.HashSet<E>newHashSetWithExpectedSize(int expectedSize)Returns a new hash set using the smallest initial table size that can holdexpectedSizeelements without resizing.static <E extends @Nullable java.lang.Object>
java.util.Set<E>newIdentityHashSet()Creates an emptySetthat uses identity to determine equality.static <E extends @Nullable java.lang.Object>
java.util.LinkedHashSet<E>newLinkedHashSet()Creates a mutable, emptyLinkedHashSetinstance.static <E extends @Nullable java.lang.Object>
java.util.LinkedHashSet<E>newLinkedHashSet(java.lang.Iterable<? extends E> elements)Creates a mutableLinkedHashSetinstance containing the given elements in order.static <E extends @Nullable java.lang.Object>
java.util.LinkedHashSet<E>newLinkedHashSetWithExpectedSize(int expectedSize)Creates aLinkedHashSetinstance, with a high enough "initial capacity" that it should holdexpectedSizeelements without growth.static <E extends @Nullable java.lang.Object>
java.util.Set<E>newSetFromMap(java.util.Map<E,java.lang.Boolean> map)Deprecated.UseCollections.newSetFromMap(java.util.Map<E, java.lang.Boolean>)instead.static <E extends java.lang.Comparable>
java.util.TreeSet<E>newTreeSet()Creates a mutable, emptyTreeSetinstance sorted by the natural sort ordering of its elements.static <E extends java.lang.Comparable>
java.util.TreeSet<E>newTreeSet(java.lang.Iterable<? extends E> elements)Creates a mutableTreeSetinstance containing the given elements sorted by their natural ordering.static <E extends @Nullable java.lang.Object>
java.util.TreeSet<E>newTreeSet(java.util.Comparator<? super E> comparator)Creates a mutable, emptyTreeSetinstance with the given comparator.static <E> java.util.Set<java.util.Set<E>>powerSet(java.util.Set<E> set)Returns the set of all possible subsets ofset.static <K extends java.lang.Comparable<? super K>>
java.util.NavigableSet<K>subSet(java.util.NavigableSet<K> set, Range<K> range)Returns a view of the portion ofsetwhose elements are contained byrange.static <E extends @Nullable java.lang.Object>
Sets.SetView<E>symmetricDifference(java.util.Set<? extends E> set1, java.util.Set<? extends E> set2)Returns an unmodifiable view of the symmetric difference of two sets.static <E extends @Nullable java.lang.Object>
java.util.NavigableSet<E>synchronizedNavigableSet(java.util.NavigableSet<E> navigableSet)Returns a synchronized (thread-safe) navigable set backed by the specified navigable set.static <E extends java.lang.Enum<E>>
java.util.stream.Collector<E,?,ImmutableSet<E>>toImmutableEnumSet()Returns aCollectorthat accumulates the input elements into a newImmutableSetwith an implementation specialized for enums.static <E extends @Nullable java.lang.Object>
Sets.SetView<E>union(java.util.Set<? extends E> set1, java.util.Set<? extends E> set2)Returns an unmodifiable view of the union of two sets.static <E extends @Nullable java.lang.Object>
java.util.NavigableSet<E>unmodifiableNavigableSet(java.util.NavigableSet<E> set)Returns an unmodifiable view of the specified navigable set.
-
-
-
Method Detail
-
immutableEnumSet
@GwtCompatible(serializable=true) public static <E extends java.lang.Enum<E>> ImmutableSet<E> immutableEnumSet(E anElement, E... otherElements)
Returns an immutable set instance containing the given enum elements. Internally, the returned set will be backed by anEnumSet.The iteration order of the returned set follows the enum's iteration order, not the order in which the elements are provided to the method.
- Parameters:
anElement- one of the elements the set should containotherElements- the rest of the elements the set should contain- Returns:
- an immutable set containing those elements, minus duplicates
-
immutableEnumSet
@GwtCompatible(serializable=true) public static <E extends java.lang.Enum<E>> ImmutableSet<E> immutableEnumSet(java.lang.Iterable<E> elements)
Returns an immutable set instance containing the given enum elements. Internally, the returned set will be backed by anEnumSet.The iteration order of the returned set follows the enum's iteration order, not the order in which the elements appear in the given collection.
- Parameters:
elements- the elements, all of the sameenumtype, that the set should contain- Returns:
- an immutable set containing those elements, minus duplicates
-
toImmutableEnumSet
public static <E extends java.lang.Enum<E>> java.util.stream.Collector<E,?,ImmutableSet<E>> toImmutableEnumSet()
Returns aCollectorthat accumulates the input elements into a newImmutableSetwith an implementation specialized for enums. UnlikeImmutableSet.toImmutableSet(), the resulting set will iterate over elements in their enum definition order, not encounter order.- Since:
- 21.0
-
newEnumSet
public static <E extends java.lang.Enum<E>> java.util.EnumSet<E> newEnumSet(java.lang.Iterable<E> iterable, java.lang.Class<E> elementType)
Returns a new, mutableEnumSetinstance containing the given elements in their natural order. This method behaves identically toEnumSet.copyOf(Collection), but also accepts non-Collectioniterables and empty iterables.
-
newHashSet
public static <E extends @Nullable java.lang.Object> java.util.HashSet<E> newHashSet()
Creates a mutable, initially emptyHashSetinstance.Note: if mutability is not required, use
ImmutableSet.of()instead. IfEis anEnumtype, useEnumSet.noneOf(java.lang.Class<E>)instead. Otherwise, strongly consider using aLinkedHashSetinstead, at the cost of increased memory footprint, to get deterministic iteration behavior.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
HashSetconstructor directly, taking advantage of "diamond" syntax.
-
newHashSet
public static <E extends @Nullable java.lang.Object> java.util.HashSet<E> newHashSet(E... elements)
Creates a mutableHashSetinstance initially containing the given elements.Note: if elements are non-null and won't be added or removed after this point, use
ImmutableSet.of()orImmutableSet.copyOf(Object[])instead. IfEis anEnumtype, useEnumSet.of(Enum, Enum[])instead. Otherwise, strongly consider using aLinkedHashSetinstead, at the cost of increased memory footprint, to get deterministic iteration behavior.This method is just a small convenience, either for
newHashSet(asList(...)), or for creating an empty set then callingCollections.addAll(java.util.Collection<? super T>, T...). This method is not actually very useful and will likely be deprecated in the future.
-
newHashSet
public static <E extends @Nullable java.lang.Object> java.util.HashSet<E> newHashSet(java.lang.Iterable<? extends E> elements)
Creates a mutableHashSetinstance containing the given elements. A very thin convenience for creating an empty set then callingCollection.addAll(java.util.Collection<? extends E>)orIterables.addAll(java.util.Collection<T>, java.lang.Iterable<? extends T>).Note: if mutability is not required and the elements are non-null, use
ImmutableSet.copyOf(Iterable)instead. (Or, changeelementsto be aFluentIterableand callelements.toSet().)Note: if
Eis anEnumtype, usenewEnumSet(Iterable, Class)instead.Note: if
elementsis aCollection, you don't need this method. Instead, use theHashSetconstructor directly, taking advantage of "diamond" syntax.Overall, this method is not very useful and will likely be deprecated in the future.
-
newHashSet
public static <E extends @Nullable java.lang.Object> java.util.HashSet<E> newHashSet(java.util.Iterator<? extends E> elements)
Creates a mutableHashSetinstance containing the given elements. A very thin convenience for creating an empty set and then callingIterators.addAll(java.util.Collection<T>, java.util.Iterator<? extends T>).Note: if mutability is not required and the elements are non-null, use
ImmutableSet.copyOf(Iterator)instead.Note: if
Eis anEnumtype, you should create anEnumSetinstead.Overall, this method is not very useful and will likely be deprecated in the future.
-
newHashSetWithExpectedSize
public static <E extends @Nullable java.lang.Object> java.util.HashSet<E> newHashSetWithExpectedSize(int expectedSize)
Returns a new hash set using the smallest initial table size that can holdexpectedSizeelements without resizing. Note that this is not whatHashSet(int)does, but it is what most users want and expect it to do.This behavior can't be broadly guaranteed, but has been tested with OpenJDK 1.7 and 1.8.
- Parameters:
expectedSize- the number of elements you expect to add to the returned set- Returns:
- a new, empty hash set with enough capacity to hold
expectedSizeelements without resizing - Throws:
java.lang.IllegalArgumentException- ifexpectedSizeis negative
-
newConcurrentHashSet
public static <E> java.util.Set<E> newConcurrentHashSet()
Creates a thread-safe set backed by a hash map. The set is backed by aConcurrentHashMapinstance, and thus carries the same concurrency guarantees.Unlike
HashSet, this class does NOT allownullto be used as an element. The set is serializable.- Returns:
- a new, empty thread-safe
Set - Since:
- 15.0
-
newConcurrentHashSet
public static <E> java.util.Set<E> newConcurrentHashSet(java.lang.Iterable<? extends E> elements)
Creates a thread-safe set backed by a hash map and containing the given elements. The set is backed by aConcurrentHashMapinstance, and thus carries the same concurrency guarantees.Unlike
HashSet, this class does NOT allownullto be used as an element. The set is serializable.- Parameters:
elements- the elements that the set should contain- Returns:
- a new thread-safe set containing those elements (minus duplicates)
- Throws:
java.lang.NullPointerException- ifelementsor any of its contents is null- Since:
- 15.0
-
newLinkedHashSet
public static <E extends @Nullable java.lang.Object> java.util.LinkedHashSet<E> newLinkedHashSet()
Creates a mutable, emptyLinkedHashSetinstance.Note: if mutability is not required, use
ImmutableSet.of()instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
LinkedHashSetconstructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
LinkedHashSet
-
newLinkedHashSet
public static <E extends @Nullable java.lang.Object> java.util.LinkedHashSet<E> newLinkedHashSet(java.lang.Iterable<? extends E> elements)
Creates a mutableLinkedHashSetinstance containing the given elements in order.Note: if mutability is not required and the elements are non-null, use
ImmutableSet.copyOf(Iterable)instead.Note: if
elementsis aCollection, you don't need this method. Instead, use theLinkedHashSetconstructor directly, taking advantage of "diamond" syntax.Overall, this method is not very useful and will likely be deprecated in the future.
- Parameters:
elements- the elements that the set should contain, in order- Returns:
- a new
LinkedHashSetcontaining those elements (minus duplicates)
-
newLinkedHashSetWithExpectedSize
public static <E extends @Nullable java.lang.Object> java.util.LinkedHashSet<E> newLinkedHashSetWithExpectedSize(int expectedSize)
Creates aLinkedHashSetinstance, with a high enough "initial capacity" that it should holdexpectedSizeelements without growth. This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method isn't inadvertently oversizing the returned set.- Parameters:
expectedSize- the number of elements you expect to add to the returned set- Returns:
- a new, empty
LinkedHashSetwith enough capacity to holdexpectedSizeelements without resizing - Throws:
java.lang.IllegalArgumentException- ifexpectedSizeis negative- Since:
- 11.0
-
newTreeSet
public static <E extends java.lang.Comparable> java.util.TreeSet<E> newTreeSet()
Creates a mutable, emptyTreeSetinstance sorted by the natural sort ordering of its elements.Note: if mutability is not required, use
ImmutableSortedSet.of()instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
TreeSetconstructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
TreeSet
-
newTreeSet
public static <E extends java.lang.Comparable> java.util.TreeSet<E> newTreeSet(java.lang.Iterable<? extends E> elements)
Creates a mutableTreeSetinstance containing the given elements sorted by their natural ordering.Note: if mutability is not required, use
ImmutableSortedSet.copyOf(Iterable)instead.Note: If
elementsis aSortedSetwith an explicit comparator, this method has different behavior thanTreeSet(SortedSet), which returns aTreeSetwith that comparator.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
TreeSetconstructor directly, taking advantage of "diamond" syntax.This method is just a small convenience for creating an empty set and then calling
Iterables.addAll(java.util.Collection<T>, java.lang.Iterable<? extends T>). This method is not very useful and will likely be deprecated in the future.- Parameters:
elements- the elements that the set should contain- Returns:
- a new
TreeSetcontaining those elements (minus duplicates)
-
newTreeSet
public static <E extends @Nullable java.lang.Object> java.util.TreeSet<E> newTreeSet(java.util.Comparator<? super E> comparator)
Creates a mutable, emptyTreeSetinstance with the given comparator.Note: if mutability is not required, use
ImmutableSortedSet.orderedBy(comparator).build()instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
TreeSetconstructor directly, taking advantage of "diamond" syntax. One caveat to this is that theTreeSetconstructor uses a nullComparatorto mean "natural ordering," whereas this factory rejects null. Clean your code accordingly.- Parameters:
comparator- the comparator to use to sort the set- Returns:
- a new, empty
TreeSet - Throws:
java.lang.NullPointerException- ifcomparatoris null
-
newIdentityHashSet
public static <E extends @Nullable java.lang.Object> java.util.Set<E> newIdentityHashSet()
Creates an emptySetthat uses identity to determine equality. It compares object references, instead of callingequals, to determine whether a provided object matches an element in the set. For example,containsreturnsfalsewhen passed an object that equals a set member, but isn't the same instance. This behavior is similar to the wayIdentityHashMaphandles key lookups.- Since:
- 8.0
-
newCopyOnWriteArraySet
@GwtIncompatible public static <E extends @Nullable java.lang.Object> java.util.concurrent.CopyOnWriteArraySet<E> newCopyOnWriteArraySet()
Creates an emptyCopyOnWriteArraySetinstance.Note: if you need an immutable empty
Set, useCollections.emptySet()instead.- Returns:
- a new, empty
CopyOnWriteArraySet - Since:
- 12.0
-
newCopyOnWriteArraySet
@GwtIncompatible public static <E extends @Nullable java.lang.Object> java.util.concurrent.CopyOnWriteArraySet<E> newCopyOnWriteArraySet(java.lang.Iterable<? extends E> elements)
Creates aCopyOnWriteArraySetinstance containing the given elements.- Parameters:
elements- the elements that the set should contain, in order- Returns:
- a new
CopyOnWriteArraySetcontaining those elements - Since:
- 12.0
-
complementOf
@GwtIncompatible public static <E extends java.lang.Enum<E>> java.util.EnumSet<E> complementOf(java.util.Collection<E> collection)
Creates anEnumSetconsisting of all enum values that are not in the specified collection. If the collection is anEnumSet, this method has the same behavior asEnumSet.complementOf(java.util.EnumSet<E>). Otherwise, the specified collection must contain at least one element, in order to determine the element type. If the collection could be empty, usecomplementOf(Collection, Class)instead of this method.- Parameters:
collection- the collection whose complement should be stored in the enum set- Returns:
- a new, modifiable
EnumSetcontaining all values of the enum that aren't present in the given collection - Throws:
java.lang.IllegalArgumentException- ifcollectionis not anEnumSetinstance and contains no elements
-
complementOf
@GwtIncompatible public static <E extends java.lang.Enum<E>> java.util.EnumSet<E> complementOf(java.util.Collection<E> collection, java.lang.Class<E> type)
Creates anEnumSetconsisting of all enum values that are not in the specified collection. This is equivalent toEnumSet.complementOf(java.util.EnumSet<E>), but can act on any input collection, as long as the elements are of enum type.- Parameters:
collection- the collection whose complement should be stored in theEnumSettype- the type of the elements in the set- Returns:
- a new, modifiable
EnumSetinitially containing all the values of the enum not present in the given collection
-
newSetFromMap
@Deprecated public static <E extends @Nullable java.lang.Object> java.util.Set<E> newSetFromMap(java.util.Map<E,java.lang.Boolean> map)
Deprecated.UseCollections.newSetFromMap(java.util.Map<E, java.lang.Boolean>)instead.Returns a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map. In essence, this factory method provides aSetimplementation corresponding to anyMapimplementation. There is no need to use this method on aMapimplementation that already has a correspondingSetimplementation (such asHashMaporTreeMap).Each method invocation on the set returned by this method results in exactly one method invocation on the backing map or its
keySetview, with one exception. TheaddAllmethod is implemented as a sequence ofputinvocations on the backing map.The specified map must be empty at the time this method is invoked, and should not be accessed directly after this method returns. These conditions are ensured if the map is created empty, passed directly to this method, and no reference to the map is retained, as illustrated in the following code fragment:
Set<Object> identityHashSet = Sets.newSetFromMap( new IdentityHashMap<Object, Boolean>());The returned set is serializable if the backing map is.
- Parameters:
map- the backing map- Returns:
- the set backed by the map
- Throws:
java.lang.IllegalArgumentException- ifmapis not empty
-
union
public static <E extends @Nullable java.lang.Object> Sets.SetView<E> union(java.util.Set<? extends E> set1, java.util.Set<? extends E> set2)
Returns an unmodifiable view of the union of two sets. The returned set contains all elements that are contained in either backing set. Iterating over the returned set iterates first over all the elements ofset1, then over each element ofset2, in order, that is not contained inset1.Results are undefined if
set1andset2are sets based on different equivalence relations, for example ifset1is aHashSetandset2is aTreeSetor theMap.keySet()of anIdentityHashMap.
-
intersection
public static <E extends @Nullable java.lang.Object> Sets.SetView<E> intersection(java.util.Set<E> set1, java.util.Set<?> set2)
Returns an unmodifiable view of the intersection of two sets. The returned set contains all elements that are contained by both backing sets. The iteration order of the returned set matches that ofset1.Results are undefined if
set1andset2are sets based on different equivalence relations, for example ifset1is aHashSetandset2is aTreeSetor theMap.keySet()of anIdentityHashMap.Note: The returned view performs slightly better when
set1is the smaller of the two sets. If you have reason to believe one of your sets will generally be smaller than the other, pass it first. Unfortunately, since this method sets the generic type of the returned set based on the type of the first set passed, this could in rare cases force you to make a cast, for example:Set<Object> aFewBadObjects = ... Set<String> manyBadStrings = ... // impossible for a non-String to be in the intersection SuppressWarnings("unchecked") Set<String> badStrings = (Set) Sets.intersection( aFewBadObjects, manyBadStrings);This is unfortunate, but should come up only very rarely.
-
difference
public static <E extends @Nullable java.lang.Object> Sets.SetView<E> difference(java.util.Set<E> set1, java.util.Set<?> set2)
Returns an unmodifiable view of the difference of two sets. The returned set contains all elements that are contained byset1and not contained byset2.set2may also contain elements not present inset1; these are simply ignored. The iteration order of the returned set matches that ofset1.Results are undefined if
set1andset2are sets based on different equivalence relations, for example ifset1is aHashSetandset2is aTreeSetor theMap.keySet()of anIdentityHashMap.
-
symmetricDifference
public static <E extends @Nullable java.lang.Object> Sets.SetView<E> symmetricDifference(java.util.Set<? extends E> set1, java.util.Set<? extends E> set2)
Returns an unmodifiable view of the symmetric difference of two sets. The returned set contains all elements that are contained in eitherset1orset2but not in both. The iteration order of the returned set is undefined.Results are undefined if
set1andset2are sets based on different equivalence relations, for example ifset1is aHashSetandset2is aTreeSetor theMap.keySet()of anIdentityHashMap.- Since:
- 3.0
-
filter
public static <E extends @Nullable java.lang.Object> java.util.Set<E> filter(java.util.Set<E> unfiltered, Predicate<? super E> predicate)
Returns the elements ofunfilteredthat satisfy a predicate. The returned set is a live view ofunfiltered; changes to one affect the other.The resulting set's iterator does not support
remove(), but all other set methods are supported. When given an element that doesn't satisfy the predicate, the set'sadd()andaddAll()methods throw anIllegalArgumentException. When methods such asremoveAll()andclear()are called on the filtered set, only elements that satisfy the filter will be removed from the underlying set.The returned set isn't threadsafe or serializable, even if
unfilteredis.Many of the filtered set's methods, such as
size(), iterate across every element in the underlying set and determine which elements satisfy the filter. When a live view is not needed, it may be faster to copyIterables.filter(unfiltered, predicate)and use the copy.Warning:
predicatemust be consistent with equals, as documented atPredicate.apply(T). Do not provide a predicate such asPredicates.instanceOf(ArrayList.class), which is inconsistent with equals. (SeeIterables.filter(Iterable, Class)for related functionality.)Java 8 users: many use cases for this method are better addressed by
Stream.filter(java.util.function.Predicate<? super T>). This method is not being deprecated, but we gently encourage you to migrate to streams.
-
filter
public static <E extends @Nullable java.lang.Object> java.util.SortedSet<E> filter(java.util.SortedSet<E> unfiltered, Predicate<? super E> predicate)
Returns the elements of aSortedSet,unfiltered, that satisfy a predicate. The returned set is a live view ofunfiltered; changes to one affect the other.The resulting set's iterator does not support
remove(), but all other set methods are supported. When given an element that doesn't satisfy the predicate, the set'sadd()andaddAll()methods throw anIllegalArgumentException. When methods such asremoveAll()andclear()are called on the filtered set, only elements that satisfy the filter will be removed from the underlying set.The returned set isn't threadsafe or serializable, even if
unfilteredis.Many of the filtered set's methods, such as
size(), iterate across every element in the underlying set and determine which elements satisfy the filter. When a live view is not needed, it may be faster to copyIterables.filter(unfiltered, predicate)and use the copy.Warning:
predicatemust be consistent with equals, as documented atPredicate.apply(T). Do not provide a predicate such asPredicates.instanceOf(ArrayList.class), which is inconsistent with equals. (SeeIterables.filter(Iterable, Class)for related functionality.)- Since:
- 11.0
-
filter
@GwtIncompatible public static <E extends @Nullable java.lang.Object> java.util.NavigableSet<E> filter(java.util.NavigableSet<E> unfiltered, Predicate<? super E> predicate)
Returns the elements of aNavigableSet,unfiltered, that satisfy a predicate. The returned set is a live view ofunfiltered; changes to one affect the other.The resulting set's iterator does not support
remove(), but all other set methods are supported. When given an element that doesn't satisfy the predicate, the set'sadd()andaddAll()methods throw anIllegalArgumentException. When methods such asremoveAll()andclear()are called on the filtered set, only elements that satisfy the filter will be removed from the underlying set.The returned set isn't threadsafe or serializable, even if
unfilteredis.Many of the filtered set's methods, such as
size(), iterate across every element in the underlying set and determine which elements satisfy the filter. When a live view is not needed, it may be faster to copyIterables.filter(unfiltered, predicate)and use the copy.Warning:
predicatemust be consistent with equals, as documented atPredicate.apply(T). Do not provide a predicate such asPredicates.instanceOf(ArrayList.class), which is inconsistent with equals. (SeeIterables.filter(Iterable, Class)for related functionality.)- Since:
- 14.0
-
cartesianProduct
public static <B> java.util.Set<java.util.List<B>> cartesianProduct(java.util.List<? extends java.util.Set<? extends B>> sets)
Returns every possible list that can be formed by choosing one element from each of the given sets in order; the "n-ary Cartesian product" of the sets. For example:Sets.cartesianProduct(ImmutableList.of( ImmutableSet.of(1, 2), ImmutableSet.of("A", "B", "C")))returns a set containing six lists:
ImmutableList.of(1, "A")ImmutableList.of(1, "B")ImmutableList.of(1, "C")ImmutableList.of(2, "A")ImmutableList.of(2, "B")ImmutableList.of(2, "C")
The result is guaranteed to be in the "traditional", lexicographical order for Cartesian products that you would get from nesting for loops:
for (B b0 : sets.get(0)) { for (B b1 : sets.get(1)) { ... ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); // operate on tuple } }Note that if any input set is empty, the Cartesian product will also be empty. If no sets at all are provided (an empty list), the resulting Cartesian product has one element, an empty list (counter-intuitive, but mathematically consistent).
Performance notes: while the cartesian product of sets of size
m, n, pis a set of sizem x n x p, its actual memory consumption is much smaller. When the cartesian set is constructed, the input sets are merely copied. Only as the resulting set is iterated are the individual lists created, and these are not retained after iteration.- Type Parameters:
B- any common base class shared by all axes (often justObject)- Parameters:
sets- the sets to choose elements from, in the order that the elements chosen from those sets should appear in the resulting lists- Returns:
- the Cartesian product, as an immutable set containing immutable lists
- Throws:
java.lang.NullPointerException- ifsets, any one of thesets, or any element of a provided set is nulljava.lang.IllegalArgumentException- if the cartesian product size exceeds theintrange- Since:
- 2.0
-
cartesianProduct
@SafeVarargs public static <B> java.util.Set<java.util.List<B>> cartesianProduct(java.util.Set<? extends B>... sets)
Returns every possible list that can be formed by choosing one element from each of the given sets in order; the "n-ary Cartesian product" of the sets. For example:Sets.cartesianProduct( ImmutableSet.of(1, 2), ImmutableSet.of("A", "B", "C"))returns a set containing six lists:
ImmutableList.of(1, "A")ImmutableList.of(1, "B")ImmutableList.of(1, "C")ImmutableList.of(2, "A")ImmutableList.of(2, "B")ImmutableList.of(2, "C")
The result is guaranteed to be in the "traditional", lexicographical order for Cartesian products that you would get from nesting for loops:
for (B b0 : sets.get(0)) { for (B b1 : sets.get(1)) { ... ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); // operate on tuple } }Note that if any input set is empty, the Cartesian product will also be empty. If no sets at all are provided (an empty list), the resulting Cartesian product has one element, an empty list (counter-intuitive, but mathematically consistent).
Performance notes: while the cartesian product of sets of size
m, n, pis a set of sizem x n x p, its actual memory consumption is much smaller. When the cartesian set is constructed, the input sets are merely copied. Only as the resulting set is iterated are the individual lists created, and these are not retained after iteration.- Type Parameters:
B- any common base class shared by all axes (often justObject)- Parameters:
sets- the sets to choose elements from, in the order that the elements chosen from those sets should appear in the resulting lists- Returns:
- the Cartesian product, as an immutable set containing immutable lists
- Throws:
java.lang.NullPointerException- ifsets, any one of thesets, or any element of a provided set is nulljava.lang.IllegalArgumentException- if the cartesian product size exceeds theintrange- Since:
- 2.0
-
powerSet
@GwtCompatible(serializable=false) public static <E> java.util.Set<java.util.Set<E>> powerSet(java.util.Set<E> set)
Returns the set of all possible subsets ofset. For example,powerSet(ImmutableSet.of(1, 2))returns the set{{}, {1}, {2}, {1, 2}}.Elements appear in these subsets in the same iteration order as they appeared in the input set. The order in which these subsets appear in the outer set is undefined. Note that the power set of the empty set is not the empty set, but a one-element set containing the empty set.
The returned set and its constituent sets use
equalsto decide whether two elements are identical, even if the input set uses a different concept of equivalence.Performance notes: while the power set of a set with size
nis of size2^n, its memory usage is onlyO(n). When the power set is constructed, the input set is merely copied. Only as the power set is iterated are the individual subsets created, and these subsets themselves occupy only a small constant amount of memory.- Parameters:
set- the set of elements to construct a power set from- Returns:
- the power set, as an immutable set of immutable sets
- Throws:
java.lang.IllegalArgumentException- ifsethas more than 30 unique elements (causing the power set size to exceed theintrange)java.lang.NullPointerException- ifsetis or containsnull- Since:
- 4.0
- See Also:
- Power set article at Wikipedia
-
combinations
public static <E> java.util.Set<java.util.Set<E>> combinations(java.util.Set<E> set, int size)
Returns the set of all subsets ofsetof sizesize. For example,combinations(ImmutableSet.of(1, 2, 3), 2)returns the set{{1, 2}, {1, 3}, {2, 3}}.Elements appear in these subsets in the same iteration order as they appeared in the input set. The order in which these subsets appear in the outer set is undefined.
The returned set and its constituent sets use
equalsto decide whether two elements are identical, even if the input set uses a different concept of equivalence.Performance notes: the memory usage of the returned set is only
O(n). When the result set is constructed, the input set is merely copied. Only as the result set is iterated are the individual subsets created. Each of these subsets occupies an additional O(n) memory but only for as long as the user retains a reference to it. That is, the set returned bycombinationsdoes not retain the individual subsets.- Parameters:
set- the set of elements to take combinations ofsize- the number of elements per combination- Returns:
- the set of all combinations of
sizeelements fromset - Throws:
java.lang.IllegalArgumentException- ifsizeis not between 0 andset.size()inclusivejava.lang.NullPointerException- ifsetis or containsnull- Since:
- 23.0
-
unmodifiableNavigableSet
public static <E extends @Nullable java.lang.Object> java.util.NavigableSet<E> unmodifiableNavigableSet(java.util.NavigableSet<E> set)
Returns an unmodifiable view of the specified navigable set. This method allows modules to provide users with "read-only" access to internal navigable sets. Query operations on the returned set "read through" to the specified set, and attempts to modify the returned set, whether direct or via its collection views, result in anUnsupportedOperationException.The returned navigable set will be serializable if the specified navigable set is serializable.
Java 8 users and later: Prefer
Collections.unmodifiableNavigableSet(java.util.NavigableSet<T>).- Parameters:
set- the navigable set for which an unmodifiable view is to be returned- Returns:
- an unmodifiable view of the specified navigable set
- Since:
- 12.0
-
synchronizedNavigableSet
@GwtIncompatible public static <E extends @Nullable java.lang.Object> java.util.NavigableSet<E> synchronizedNavigableSet(java.util.NavigableSet<E> navigableSet)
Returns a synchronized (thread-safe) navigable set backed by the specified navigable set. In order to guarantee serial access, it is critical that all access to the backing navigable set is accomplished through the returned navigable set (or its views).It is imperative that the user manually synchronize on the returned sorted set when iterating over it or any of its
descendingSet,subSet,headSet, ortailSetviews.NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); ... synchronized (set) { // Must be in the synchronized block Iterator<E> it = set.iterator(); while (it.hasNext()) { foo(it.next()); } }or:
NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); NavigableSet<E> set2 = set.descendingSet().headSet(foo); ... synchronized (set) { // Note: set, not set2!!! // Must be in the synchronized block Iterator<E> it = set2.descendingIterator(); while (it.hasNext()) foo(it.next()); }}Failure to follow this advice may result in non-deterministic behavior.
The returned navigable set will be serializable if the specified navigable set is serializable.
Java 8 users and later: Prefer
Collections.synchronizedNavigableSet(java.util.NavigableSet<T>).- Parameters:
navigableSet- the navigable set to be "wrapped" in a synchronized navigable set.- Returns:
- a synchronized view of the specified navigable set.
- Since:
- 13.0
-
subSet
@GwtIncompatible public static <K extends java.lang.Comparable<? super K>> java.util.NavigableSet<K> subSet(java.util.NavigableSet<K> set, Range<K> range)
Returns a view of the portion ofsetwhose elements are contained byrange.This method delegates to the appropriate methods of
NavigableSet(namelysubSet(),tailSet(), andheadSet()) to actually construct the view. Consult these methods for a full description of the returned view's behavior.Warning:
Ranges always represent a range of values using the values' natural ordering.NavigableSeton the other hand can specify a custom ordering via aComparator, which can violate the natural ordering. Using this method (or in general usingRange) with unnaturally-ordered sets can lead to unexpected and undefined behavior.- Since:
- 20.0
-
-