Class Collections
Meta-Stability
A collection is called meta-stable if and only if its encounter
order (the order of elements as seen through iterators) remains the same
unless a change of content occurs. What constitutes a change of
content may depend on the semantics of the particular implementation. We
consider the following criteria as indicative that a change of content of
collection c has occurred between time points t1 and
t2:
- A copy of
chas been obtained asd = new OtherCollection(c)att1;c.equals(d)returnstrueatt1butfalseatt2. - An iterator over
chas been obtained asi = c.iterator()att1; an attempt to use it throwsConcurrentModificationExceptionatt2.
This property is not specified in the JDK collection framework, but applies to many common implementations:
- Lists (
ArrayList,LinkedList, etc.) are always meta-stable. - Ordered collections (
TreeSet,TreeMap, etc.) are always meta-stable. - Hybrid hash-based collections (
LinkedHashSet,LinkedHashMap) are always meta-stable. - Pure hash-based collections (
HashSet,HashMap) are likely meta-stable; some caution is recommended.
Collection implementations that apply spontaneous self-optimization or compute elements on the fly are not expected to be meta-stable; careful investigation is recommended before applying any operations that rely on meta-stability.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classHelper class for building maps incrementally. -
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic <K,V> Map <K, V> buildMap(Consumer<? super Collections.MapBuilder<K, V>> initializer) Builds a map using the given initializer.static <A,B, C extends B>
Map<A, B> castValues(Class<? extends C> cls, Map<A, C> things) Returns a view on a given collection that modifies the type of each element by casting.static <A> Collection<A> concat(Collection<? extends A> some, Collection<? extends A> other) Returns a collection view that contains all elements of two given collections.static <A,B> Map <B, A> Returns a map that contains all pairs of a given map with key and value swapped.static <A> List<A> Creates an independent copy of a list with behavior as similar as possible.static <A,B> Map <A, B> Creates an independent copy of a map with behavior as similar as possible.static <A,B> NavigableMap <A, B> duplicate(NavigableMap<A, B> proto) Creates an independent copy of a navigable map with behavior as similar as possible.static <A> Set<A> Creates an independent copy of a set with behavior as similar as possible.static <A,B> SortedMap <A, B> Creates an independent copy of a sorted map with behavior as similar as possible.static <A> SortedSet<A> Creates an independent copy of a sorted set with behavior as similar as possible.static <A> Set<A> elements(Collection<? extends A> things) Returns a new set of the elements of a given collection, without duplicates.static <A> SortedSet<A> elements(Collection<? extends A> things, Comparator<? super A> comparator) Returns a new set of the elements of a given collection, without duplicates according to a given ordering.static <A,B> SortedMap <A, B> Returns an unmodifiable empty sorted map.static <A> SortedSet<A> Returns an unmodifiable empty sorted set.static <A> Collection<A> flatten(Collection<? extends Collection<? extends A>> colls) Returns a view on a collection of collections that contains all of their elements.static <A> voidforEach(A[] list, ObjIntConsumer<A> code) Apply code to array elements in ascending order, together with their indicesstatic <A> voidforEach(List<A> list, ObjIntConsumer<A> code) Apply code to list elements in ascending order, together with their indices.static <A> intReturn the index of the first element which fulfills the given predicate.static <D> DReturn the greatest member of a given nonempty set which is less or equal the given upper bound.static <D> DinfimumKey(SortedMap<D, ?> map, D key) Return the greatest key in the domain of a given nonempty map which is less or equal the upper bound.static <A> Set<A> intersection(Collection<? extends A> some, Collection<? extends A> other) Returns a new set that contains the elements commonly contained in both given collections.static <A> AReturn the last element in a nonempty list.literalIntList(int... values) Returns an unmodifiable list of the given elements.static <A> List<A> literalList(A... values) Returns an unmodifiable list of the given elements.static <A,B> Collections.MapBuilder <A, B> literalMap(A a, B b) Starts the incremental creation of a map with one entry.static <A> Set<A> literalSet(A... values) Returns an unmodifiable set of the given elements.static <A> Set<A> setminus(Collection<? extends A> some, Collection<? extends A> other) Returns a new set that contains the elements contained in one given collection but not the other.static <A extends Comparable<? super A>,B>
SortedMap<A, B> singletonSortedMap(A key, B value) Returns an unmodifiable sorted map with one entry.static <A,B> SortedMap <A, B> singletonSortedMap(Comparator<? super A> comparator, A key, B value) Returns an unmodifiable sorted map with one entry and a given ordering.static <A extends Comparable<? super A>>
SortedSet<A> singletonSortedSet(A elem) Returns an unmodifiable sorted set with one element.static <A> SortedSet<A> singletonSortedSet(Comparator<? super A> comparator, A elem) Returns an unmodifiable sorted set with one element and a given ordering.static <T> Tsome(Collection<T> set) Finds an arbitrary element contained in a collection.static <T> Tthe(Collection<T> set) Finds the single element contained in a collection.static <A,B> Map <A, B> Returns a map with a given key set and values computed by a function.static <A,B, C> Map <B, C> toSpan(Function<? super A, ? extends B> left, Function<? super A, ? extends C> right, Collection<? extends A> gen) Creates a map by generating entries from generating elements using two functions.static <A,B, C> Map <B, C> toSpan(Function<? super A, ? extends B> left, Function<? super A, ? extends C> right, BiFunction<? super C, ? super C, ? extends C> merge, Collection<? extends A> gen) Creates a map by generating entries from generating elements using two functions.static <A> Set<A> union(Collection<? extends A> some, Collection<? extends A> other) Returns a new set that contains the elements contained in either of the given collections.static <K,V> Map.Entry <K, V> unmodifiableEntry(Map.Entry<? extends K, ? extends V> entry) Returns an unmodifiable view on a given map entry.
-
Field Details
-
METHOD_NAME_CLONE
The name of the clone method.- See Also:
-
-
Method Details
-
the
Finds the single element contained in a collection.- Type Parameters:
T- the type of elements- Parameters:
set- a collection of elements of size 1- Returns:
- the single element contained in the collection
- Throws:
IllegalArgumentException- ifsetcontains none, or more than one element- See Also:
-
some
Finds an arbitrary element contained in a collection. As long as the collection is meta-stable, the returned element will not change.- Type Parameters:
T- the type of elements- Parameters:
set- a nonempty collection of elements- Returns:
- an arbitrary element contained in the collection
- Throws:
IllegalArgumentException- ifsetcontains no element- See Also:
-
literalSet
Returns an unmodifiable set of the given elements.Use this method where the behavior of the alternative
Set.of(Object[])is not appropriate.- Type Parameters:
A- the type of elements- Parameters:
values- an array of elements- Returns:
- a set containing exactly the given elements
- See Also:
-
literalList
Returns an unmodifiable list of the given elements.Use this method where the behavior of the alternative
List.of(Object[])is not appropriate.- Type Parameters:
A- the type of elements- Parameters:
values- an array of elements- Returns:
- a list containing exactly the given elements in the same order
- See Also:
-
literalIntList
Returns an unmodifiable list of the given elements.- Parameters:
values- an array of elements- Returns:
- a list containing exactly the given elements (boxed) in the same order
-
toSpan
public static <A,B, Map<B,C> C> toSpan(Function<? super A, ? extends B> left, Function<? super A, ? extends C> right, Collection<? extends A> gen) Creates a map by generating entries from generating elements using two functions.- Type Parameters:
A- the type of generating elemensB- the type of keysC- the type of values- Parameters:
left- the key-generating functionright- the value-generating functiongen- the generating elements- Returns:
- an unmodifiable map that contains, for each generating element, the computed entry
- Throws:
IllegalArgumentException- if two generating elements result in the same key but different values
-
toSpan
public static <A,B, Map<B,C> C> toSpan(Function<? super A, ? extends B> left, Function<? super A, ? extends C> right, BiFunction<? super C, ? super C, ? extends C> merge, Collection<? extends A> gen) Creates a map by generating entries from generating elements using two functions.- Type Parameters:
A- the type of generating elemensB- the type of keysC- the type of values- Parameters:
left- the key-generating functionright- the value-generating functionmerge- an operation to reconcile values if two generating elements result in the same keygen- the generating elements- Returns:
- an unmodifiable map that contains, for each generating element, the computed entry
-
toGraph
Returns a map with a given key set and values computed by a function.- Type Parameters:
A- the type of keysB- the type of values- Parameters:
fun- a function to compute values from keysdom- the key set- Returns:
- a new map that maps all keys in
domto values computed withfun
-
concat
Returns a collection view that contains all elements of two given collections.Changes to the underlying collections are reflected in the resulting collection. By contrast, the resulting collection cannot be modified on its own.
- Type Parameters:
A- the element type- Parameters:
some- one collectionother- another collection- Returns:
- an unmodifiable collection that always contains the current elements of both given collections
- Throws:
NullPointerException- ifsomeorotheris null
-
union
Returns a new set that contains the elements contained in either of the given collections.Changes to the underlying sets are not reflected by the result.
- Type Parameters:
A- the type of elements- Parameters:
some- a collection of elementsother- another collection of elements- Returns:
- a new set that contains those elements that are contained in either
someorother
-
setminus
Returns a new set that contains the elements contained in one given collection but not the other.Changes to the underlying sets are not reflected by the result.
- Type Parameters:
A- the type of elements- Parameters:
some- a collection of elementsother- another collection of elements- Returns:
- a new set that contains those elements that are contained in
somebut not inother
-
intersection
Returns a new set that contains the elements commonly contained in both given collections.Changes to the underlying sets are not reflected by the result.
- Type Parameters:
A- the type of elements- Parameters:
some- a collection of elementsother- another collection of elements- Returns:
- a new set that contains those elements that are contained in both
someandother
-
flatten
Returns a view on a collection of collections that contains all of their elements.Changes to the underlying collection(s) are reflected by the resulting view.
- Type Parameters:
A- the type of elements- Parameters:
colls- a collection of collections of elements- Returns:
- an unmodifiable collection that contains all elements that are
contained in a collection contained in
colls
-
unmodifiableEntry
Returns an unmodifiable view on a given map entry.Changes to the underlying entry are reflected by the resulting view.
- Type Parameters:
K- the key typeV- the value type- Parameters:
entry- the entry- Returns:
- an unmodifiable map entry with the same key and value
as
entry
-
elements
Returns a new set of the elements of a given collection, without duplicates.Duplicates are element for which
Object.equals(java.lang.Object)returnstrue.- Type Parameters:
A- the type of elements- Parameters:
things- a collection of elements- Returns:
- a new set containing all elements of
things, but no duplicates
-
elements
public static <A> SortedSet<A> elements(Collection<? extends A> things, Comparator<? super A> comparator) Returns a new set of the elements of a given collection, without duplicates according to a given ordering.Duplicates are element for which
comparator.comparereturns0.- Type Parameters:
A- the type of elements- Parameters:
things- a collection of elementscomparator- a comparison function that specifies the ordering- Returns:
- a new set containing all elements of
things, but no duplicates - Throws:
IllegalArgumentException- if some elements cannot be compared
-
castValues
Returns a view on a given collection that modifies the type of each element by casting.Changes to the underlying collection are reflected by the resulting view.
- Type Parameters:
A- the type of keysB- the actual type of elementsC- the apparent type of elements- Parameters:
cls- the class to cast tothings- the map to transform- Returns:
- an unmodifiable map that has, for each current value of
things, a cast reference of typecls, for the same key
-
literalMap
Starts the incremental creation of a map with one entry.- Type Parameters:
A- the type of keysB- the type of values- Parameters:
a- the key of the initial entryb- the value of the initial entry- Returns:
- a builder for a map that already contains the given entry
- See Also:
-
buildMap
Builds a map using the given initializer.The initializer is passed a reference to a new empty
Collections.MapBuilderobject. The resulting map is created from the contents of that object once the initializer returns.- Type Parameters:
K- the type of map keysV- the type of map values- Parameters:
initializer- a piece of initializer code- Returns:
- an unmodifiable map initialized as specified
- Throws:
NullPointerException- ifinitializeris null- Since:
- 1.3
-
emptySortedSet
Returns an unmodifiable empty sorted set.- Type Parameters:
A- the type of elements- Returns:
- an unmodifiable empty sorted set
- See Also:
-
singletonSortedSet
Returns an unmodifiable sorted set with one element.- Type Parameters:
A- the type of elements- Parameters:
elem- the element- Returns:
- an unmodifiable sorted set with the given element
- See Also:
-
singletonSortedSet
Returns an unmodifiable sorted set with one element and a given ordering.- Type Parameters:
A- the type of elements- Parameters:
comparator- a comparison function that specifies the orderingelem- the element- Returns:
- an unmodifiable sorted set with the given element
- See Also:
-
emptySortedMap
Returns an unmodifiable empty sorted map.- Type Parameters:
A- the type of keysB- the type of values- Returns:
- an unmodifiable empty sorted map
- See Also:
-
singletonSortedMap
public static <A extends Comparable<? super A>,B> SortedMap<A,B> singletonSortedMap(A key, B value) Returns an unmodifiable sorted map with one entry.- Type Parameters:
A- the type of keysB- the type of values- Parameters:
key- the key of the entryvalue- the value of the entry- Returns:
- an unmodifiable sorted map with the given entry
- Throws:
NullPointerException- ifkeyis null- See Also:
-
singletonSortedMap
public static <A,B> SortedMap<A,B> singletonSortedMap(Comparator<? super A> comparator, A key, B value) Returns an unmodifiable sorted map with one entry and a given ordering.- Type Parameters:
A- the type of keysB- the type of values- Parameters:
comparator- a comparison function specifying the orderingkey- the key of the entryvalue- the value of the entry- Returns:
- an unmodifiable sorted map with the given entry
- See Also:
-
infimum
Return the greatest member of a given nonempty set which is less or equal the given upper bound.- Type Parameters:
D- the type of elements- Parameters:
set- a nonempty sorted setvalue- the upper bound- Returns:
- the greatest element of
setwhich is less or equal tovalue - Throws:
NoSuchElementException- if the given set is empty
-
infimumKey
Return the greatest key in the domain of a given nonempty map which is less or equal the upper bound.This method is not easily emulated by
infimum(SortedSet, Object), because for some reasonSortedMap.keySet()does not return aSortedSet.- Type Parameters:
D- the type of keys- Parameters:
map- a nonempty sorted mapkey- the upper bound- Returns:
- the greatest key of
mapwhich is less or equal tokey - Throws:
NoSuchElementException- if the given map is empty
-
converse
Returns a map that contains all pairs of a given map with key and value swapped.The values of the given map must be unique.
nullkeys and/or values are not supported.This operation copies map entries; later changes to the given map are not reflected.
- Type Parameters:
A- the key type of the given map; the value type of the resulting mapB- the value type of the given map; the key type of the resulting map- Parameters:
map- a map- Returns:
- an unmodifiable map of all values of the given map to their corresponding keys
- Throws:
UnsupportedOperationException- if a value is associated with more than one key
-
lastOf
Return the last element in a nonempty list.- Type Parameters:
A- the type of elements- Parameters:
list- a nonempty list- Returns:
- the last element of the list
- Throws:
IllegalArgumentException- if the list is empty
-
indexOf
Return the index of the first element which fulfills the given predicate.- Type Parameters:
A- the type of elements- Parameters:
list- the list of elements to searchfilter- the predicate for which is searched- Returns:
- the index of the first element which fulfills the given
predicate, or
-1if no such element exists. - Throws:
NullPointerException- iflistorfilteris null- Since:
- 1.2
-
forEach
Apply code to list elements in ascending order, together with their indices.- Type Parameters:
A- the type of elements- Parameters:
list- the list of elements to visitcode- to apply to all elements- Throws:
NullPointerException- iflistorcodeis null- Since:
- 1.3
-
forEach
Apply code to array elements in ascending order, together with their indices- Type Parameters:
A- the type of elements- Parameters:
list- the array of elements to visitcode- to apply to all elements- Throws:
NullPointerException- iflistorcodeis null- Since:
- 1.3
-
duplicate
Creates an independent copy of a map with behavior as similar as possible. The method tries- a clone method;
- a copy constructor;
- a nullary constructor of the class of the prototype,
- a default construction strategy, namely
to construct a
HashMap.
Whenever one of the first three strategies fails, the next is tried. This is the case not only when the method is not foreseen, but also when its execution throws an exception due to a programming error. In this case one can get a result constructed by a later strategy, other than expected.
This class provides more specialized methods
duplicate(SortedMap)andduplicate(NavigableMap).This method works heuristically. For instance, a clone method is not guaranteed to return instances of the class of the original, and a constructor with one argument of its own type is only recommended to copy all contained values.
- Type Parameters:
A- the type of the keys in the mapsB- the type of the values in the maps- Parameters:
proto- the original map to copy- Returns:
- a map that initially contains the same entries as
proto, with implementation behavior as similar as possible. - Throws:
NullPointerException- ifprotois null- Since:
- 1.2
- See Also:
-
duplicate
Creates an independent copy of a sorted map with behavior as similar as possible. In particular, the ordering of the copy and the prototype are the same. The method tries- a clone method;
- a copy constructor;
- the constructor with a
Comparatoras argument, if present in the prototype, otherwise its nullary constructor. - a default construction strategy, namely
to construction a
TreeMap.
Whenever one of the first three strategies fails, the next is tried. This is the case not only when the method is not foreseen, but also when its execution throws an exception due to a programming error. In this case one can get a result constructed by a later strategy, other than expected.
This code relies on three of the "four standard constructors" as explained with the API doc of
SortedMap.This class provides the more specialized method
duplicate(NavigableMap)and the more general methodduplicate(Map).This method works heuristically. For instance, a clone method is not guaranteed to return instances of the class of the original, and a constructor with one argument of its own type is only recommended to copy all contained values.
- Type Parameters:
A- the type of the keys in the mapsB- the type of the values in the maps- Parameters:
proto- the original sorted map to copy- Returns:
- a sorted map that initially contains the same entries as
proto, with implementation behavior as similar as possible. - Throws:
NullPointerException- ifprotois null- Since:
- 1.2
- See Also:
-
duplicate
Creates an independent copy of a set with behavior as similar as possible. The method tries- a clone method;
- a copy constructor;
- the nullary constructor of the prototype:
- a default strategy, namely to construct a
HashSet.
Whenever one of the first three strategies fails, the next is tried. This is the case not only when the method is not foreseen, but also when its execution throws an exception due to a programming error. In this case one can get a result constructed by a later strategy, other than expected.
This class provides the more specialized method
duplicate(SortedSet).This method works heuristically. For instance, a clone method is not guaranteed to return instances of the class of the original, and a constructor with one argument of its own type is only recommended to copy all contained values.
- Type Parameters:
A- the type of the set elements- Parameters:
proto- the original set to copy- Returns:
- a set that initially contains the same entries as
proto, with implementation behavior as similar as possible. - Throws:
NullPointerException- ifprotois null- Since:
- 1.2
- See Also:
-
duplicate
Creates an independent copy of a sorted set with behavior as similar as possible. In particular, the ordering of the copy and the prototype are the same. The method tries- a clone method;
- a copy constructor;
- the constructor with a
Comparatoras argument, if present in the prototype, otherwise its nullary constructor. - a default construction strategy, namely
to construction a
TreeSet.
Whenever one of the first three strategies fails, the next is tried. This is the case not only when the method is not foreseen, but also when its execution throws an exception due to a programming error. In this case one can get a result constructed by a later strategy, other than expected.
This class provides the more general method
duplicate(Set).This method works heuristically. For instance, a clone method is not guaranteed to return instances of the class of the original, and a constructor with one argument of its own type is only recommended to copy all contained values.
- Type Parameters:
A- the type of the set elements- Parameters:
proto- the original sorted set to copy- Returns:
- a sorted set that initially contains the same entries as
proto, with implementation behavior as similar as possible. - Throws:
NullPointerException- ifprotois null- Since:
- 1.2
- See Also:
-
duplicate
Creates an independent copy of a list with behavior as similar as possible. The method tries- a clone method;
- a copy constructor;
- the prototype's nullary constructor.
- a default construction strategy, namely
to construct an
ArrayList.
Whenever one of the first three strategies fails, the next is tried. This is the case not only when the method is not foreseen, but also when its execution throws an exception due to a programming error. In this case one can get a result constructed by a later strategy, other than expected.
This method works heuristically. For instance, a clone method is not guaranteed to return instances of the class of the original, and a constructor with one argument of its own type is only recommended to copy all contained values.
- Type Parameters:
A- the type of the list elements- Parameters:
proto- the original list to copy- Returns:
- a list that initially contains the same entries as
proto, with implementation behavior as similar as possible. - Throws:
NullPointerException- ifprotois null- Since:
- 1.2
- See Also:
-