Class Containers
Collection and CheckedContainer.
Some methods are extensions to the standard Collections utility class.
Null values
Most methods in this class accepts null argument values, and collections or arrays containing null elements. By contrast, the standard static methods ofList, Set and Map interfaces reject null values.
These standard methods should be preferred when null values would be error.
Element order
All methods in this class preserve element order, including the methods returning aSet.- Since:
- 0.3
-
Method Summary
Modifier and TypeMethodDescriptionstatic <E extends Comparable<E>>
intCompares element-by-element the values provided by two iterators, in iteration order.static <E> List<E> copyToImmutableList(Collection<? extends E> collection, Class<E> elementType) Copies the content of the specified collection in an immutable list, or returnsnullif the collection is null.static <E> Set<E> copyToImmutableSet(E... elements) Copies the content of the specified array in an immutable set, or returnsnullif the array is null.static <E> Set<E> copyToImmutableSetIgnoreNull(E... elements) Copies the non-null elements of the specified array in an immutable set, or returnsnullif the array is null.static <S,E> List <E> derivedList(List<S> storage, Function<S, E> converter) Returns a list whose elements are derived on-the-fly from the given list.static <SK,SV, K, V>
Map<K, V> derivedMap(Map<SK, SV> storage, ObjectConverter<SK, K> keyConverter, ObjectConverter<SV, V> valueConverter) Returns a map whose keys and values are derived on-the-fly from the given map.static <S,E> Set <E> derivedSet(Set<S> storage, ObjectConverter<S, E> converter) Returns a set whose elements are derived on-the-fly from the given set.static <E> Queue<E> Returns a queue which is always empty and accepts no element.static inthashMapCapacity(int count) Returns the capacity to give to theHashMapandHashSetconstructors for holding the given number of elements.static booleanisNullOrEmpty(Collection<?> collection) Returnstrueif the given collection is either null or empty.static booleanisNullOrEmpty(Map<?, ?> map) Returnstrueif the given map is either null or empty.static <E> List<E> newCheckedList(Collection<? extends E> collection, Class<E> elementType) Creates a dynamically type-safe and null-safe list.static <E> Set<E> newCheckedSet(Collection<? extends E> collection, Class<E> elementType) Creates a dynamically type-safe and null-safe set.static <E> Collection<E> nonNull(Collection<E> collection) Returns the given collection, orCollections.EMPTY_SETif the given collection is null.static <E> Set<E> Returns the given set, orCollections.EMPTY_SETif the given set is null.static <T> TpeekFirst(Iterable<T> collection) Returns the first element of the given iterable, ornullif none.static <T> TpeekIfSingleton(Iterable<T> collection) If the given iterable contains exactly one non-null element, returns that element.static <T> TReturns the value mapped to the given key cast to the given type, ornullif the map is null or does not contain a value for the key.static <E> Set<E> singletonOrEmpty(E element) Returns the given value as a singleton if non-null, or returns an empty set otherwise.static Collection<?> toCollection(Object object) Returns the given object as a collection.static <E> List<E> unmodifiable(List<E> list) Returns an unmodifiable view or copy of the given list.static <K,V> Map <K, V> unmodifiable(Map<K, V> map) Returns an unmodifiable view or copy of the given map.static <E> Set<E> unmodifiable(Set<E> set) Returns an unmodifiable view or copy of the given set.static <E> List<? extends E> unmodifiableList(E... array) Deprecated, for removal: This API element is subject to removal in a future version.static <E> List<? extends E> unmodifiableList(E[] array, int lower, int upper) Deprecated, for removal: This API element is subject to removal in a future version.Renamed asviewAsUnmodifiableList(Object[], int, int)for clarity.static <E> List<E> viewAsUnmodifiableList(E... array) Returns an unmodifiable view of the given array.static <E> List<E> viewAsUnmodifiableList(E[] array, int lower, int upper) Returns an unmodifiable view of a subregion of the given array.
-
Method Details
-
emptyQueue
Returns a queue which is always empty and accepts no element.- Type Parameters:
E- the type of elements in the empty queue.- Returns:
- an empty queue.
- Since:
- 1.6
- See Also:
-
isNullOrEmpty
Returnstrueif the given collection is either null or empty. If this method returnsfalse, then the given collection is guaranteed to be non-null and to contain at least one element.This is a convenience method for classes implementing the lazy instantiation pattern. In such cases, null collections (i.e. collections not yet instantiated) are typically considered as empty.
- Parameters:
collection- the collection to test, ornull.- Returns:
trueif the given collection is null or empty, orfalseotherwise.
-
isNullOrEmpty
Returnstrueif the given map is either null or empty. If this method returnsfalse, then the given map is guaranteed to be non-null and to contain at least one element.This is a convenience method for classes implementing the lazy instantiation pattern. In such cases, null maps (i.e. maps not yet instantiated) are typically considered as empty.
- Parameters:
map- the map to test, ornull.- Returns:
trueif the given map is null or empty, orfalseotherwise.
-
nonNull
Returns the given collection, orCollections.EMPTY_SETif the given collection is null. In the latter case, the returned collection is tolerant to calls tocontains(null)andclear().- Type Parameters:
E- the type of elements in the collection.- Parameters:
collection- the collection, ornull.- Returns:
- the given collection, or an empty collection if the given collection was null.
- Since:
- 1.6
-
nonNull
Returns the given set, orCollections.EMPTY_SETif the given set is null. In the latter case, the returned set is tolerant to calls tocontains(null)andclear().- Type Parameters:
E- the type of elements in the collection.- Parameters:
set- the collection, ornull.- Returns:
- the given collection, or an empty set if the given collection was null.
- Since:
- 1.6
-
peekFirst
Returns the first element of the given iterable, ornullif none. If the iterable contains more than one element, the remaining elements are ignored. Consequently, this method should be used only when multi-occurrence is not ambiguous.This method is null-safe. Note however that the first element may be null. This method does not distinguish between an empty collection and a collection containing null elements.
- Type Parameters:
T- the type of elements contained in the iterable.- Parameters:
collection- the iterable from which to get the first element, ornull.- Returns:
- the first element, or
nullif the given iterable is null or empty. - Since:
- 1.6
- See Also:
-
peekIfSingleton
If the given iterable contains exactly one non-null element, returns that element. Otherwise returnsnull. This is a variant ofpeekFirst(Iterable)where remaining elements are not ignored.- Type Parameters:
T- the type of elements contained in the iterable.- Parameters:
collection- the iterable from which to get the singleton element, ornull.- Returns:
- the singleton element, or
nullif the given iterable is null or does not contain exactly one non-null element. - Since:
- 1.6
-
singletonOrEmpty
Returns the given value as a singleton if non-null, or returns an empty set otherwise.- Type Parameters:
E- the element type.- Parameters:
element- the element to return in a collection if non-null.- Returns:
- a collection containing the given element if non-null, or an empty collection otherwise.
- Since:
- 1.6
- See Also:
-
copyToImmutableSetIgnoreNull
Copies the non-null elements of the specified array in an immutable set, or returnsnullif the array is null. This method does the same work ascopyToImmutableSet(Object...)except that null elements are silently ignored.- Type Parameters:
E- the type of array elements.- Parameters:
elements- the array to copy in a set. May benullor contain null elements.- Returns:
- an immutable set containing the non-null array elements, or
nullif the given array was null. - Since:
- 1.6
- See Also:
-
copyToImmutableSet
Copies the content of the specified array in an immutable set, or returnsnullif the array is null. If the given array contains duplicated elements in the sense ofObject.equals(Object), then the returned set will contain an arbitrary instance among the duplicated values. If the array contains somenullelements, then the returned set contains one null element.Differences with standard
This method differs fromSet.of(…)methodSet.of(Object...)in that it preserves element order, accepts null argument, accepts null elements and does not throwIllegalArgumentExceptionif the array contains duplicated elements.- Type Parameters:
E- the type of array elements.- Parameters:
elements- the array to copy in a set. May benullor contain null elements.- Returns:
- an immutable set containing the array elements, or
nullif the given array was null. - Since:
- 1.6
- See Also:
-
copyToImmutableList
public static <E> List<E> copyToImmutableList(Collection<? extends E> collection, Class<E> elementType) Copies the content of the specified collection in an immutable list, or returnsnullif the collection is null. The returned list implements theCheckedContainerinterface.Differences with standard
This method differs fromList.of(…)methodList.of(Object...)in that it accepts null argument, accepts null array elements, and returns a list implementingCheckedContainer.- Type Parameters:
E- the type of collection elements.- Parameters:
collection- the collection to copy in a list. May benullor contain null elements.elementType- type of elements. This value will be returned byCheckedContainer.getElementType().- Returns:
- an immutable list containing the collection elements, or
nullif the given collection was null. - Since:
- 1.6
- See Also:
-
viewAsUnmodifiableList
Returns an unmodifiable view of the given array. A direct reference to the given array is retained (i.e. the array is not cloned). Consequently, the given array shall not be modified after construction if the returned list is intended to be immutable.The returned list implements the
CheckedContainerinterface. The value returned by itsCheckedContainer.getElementType()method is inferred from the array component type.- Type Parameters:
E- the base type of elements in the list.- Parameters:
array- the array to wrap, ornullif none.- Returns:
- the given array wrapped in an unmodifiable list, or
nullif the given array was null. - Since:
- 1.6
- See Also:
-
viewAsUnmodifiableList
Returns an unmodifiable view of a subregion of the given array. A direct reference to the given array is retained (i.e. the array is not cloned). Consequently, the specified sub-region of the given array shall not be modified after construction if the returned list is intended to be immutable.The returned list implements the
CheckedContainerinterface. The value returned by itsCheckedContainer.getElementType()method is inferred from the array component type.- Type Parameters:
E- the type of elements in the list.- Parameters:
array- the array to wrap (cannot be null).lower- low endpoint (inclusive) of the sublist.upper- high endpoint (exclusive) of the sublist.- Returns:
- the given array wrapped in an unmodifiable list.
- Throws:
IndexOutOfBoundsException- if the lower or upper value are out of bounds.- Since:
- 1.6
-
unmodifiableList
@SafeVarargs @Deprecated(since="1.6", forRemoval=true) public static <E> List<? extends E> unmodifiableList(E... array) Deprecated, for removal: This API element is subject to removal in a future version.Renamed asviewAsUnmodifiableList(Object...)for clarity. The new name emphases the contrast withcopyToImmutableList(Collection, Class). The parameterized return type is also different.Returns an unmodifiable view of the given array. A direct reference to the given array is retained (i.e. the array is not cloned).- Type Parameters:
E- the base type of elements in the list.- Parameters:
array- the array to wrap, ornullif none.- Returns:
- the given array wrapped in an unmodifiable list, or
nullif the given array was null.
-
unmodifiableList
@Deprecated(since="1.6", forRemoval=true) public static <E> List<? extends E> unmodifiableList(E[] array, int lower, int upper) Deprecated, for removal: This API element is subject to removal in a future version.Renamed asviewAsUnmodifiableList(Object[], int, int)for clarity. The new name emphases the contrast withcopyToImmutableList(Collection, Class). The parameterized return type is also different.Returns an unmodifiable view of a subregion of the given array. A direct reference to the given array is retained (i.e. the array is not cloned).- Type Parameters:
E- the type of elements in the list.- Parameters:
array- the array to wrap (cannot be null).lower- low endpoint (inclusive) of the sublist.upper- high endpoint (exclusive) of the sublist.- Returns:
- the given array wrapped in an unmodifiable list.
- Throws:
IndexOutOfBoundsException- if the lower or upper value are out of bounds.
-
unmodifiable
Returns an unmodifiable view or copy of the given list. This method is similar to the standardCollections.unmodifiableList(List)except for the following:- Accepts
nullargument, in which case this method returnsnull. - Does not guarantee that the returned list is a view of the given list. It may be a copy.
- As a result of above relaxation, returns more efficient implementations for lists of zero or one element. Such small set occurs frequently in Apache SIS.
Collections.unmodifiableList(List)method if a view is desired, orList.copyOf(Collection)otherwise.Differences with standard
This method differs fromcopyOf(…)methodList.copyOf(Collection)in that it may avoid copy, and accepts null elements.- Type Parameters:
E- the type of elements in the list.- Parameters:
list- the list to make unmodifiable, ornull.- Returns:
- an unmodifiable view or copy of the given list, or
nullif the given list was null. - Since:
- 1.6
- Accepts
-
unmodifiable
Returns an unmodifiable view or copy of the given set. This method is similar to the standardCollections.unmodifiableSet(Set)except for the following:- Accepts
nullargument, in which case this method returnsnull. - Does not guarantee that the returned set is a view of the given set. It may be a copy.
- As a result of above relaxation, returns more efficient implementations for sets of zero or one element. Such small set occurs frequently in Apache SIS, especially for names or identifiers.
Collections.unmodifiableSet(Set)method instead.Differences with standard
This method differs fromcopyOf(…)methodSet.copyOf(Collection)in that it may avoid copy, preserves element order and accepts null elements.- Type Parameters:
E- the type of elements in the set.- Parameters:
set- the set to make unmodifiable, ornull.- Returns:
- an unmodifiable view or copy of the given set, or
nullif the given set was null. - Since:
- 1.6
- Accepts
-
unmodifiable
Returns an unmodifiable view or copy of the given map. This method is similar to the standardCollections.unmodifiableMap(Map)except for the following:- Accepts
nullargument, in which case this method returnsnull. - Does not guarantee that the returned map is a view of the given map. It may be a copy.
- As a result of above relaxation, returns more efficient implementations for maps of zero or one entry. Such small map occurs frequently in Apache SIS.
Collections.unmodifiableMap(Map)method instead.Differences with standard
This method differs fromcopyOf(…)methodMap.copyOf(Map)in that it may avoid copy, preserves entry order and accepts null keys and values.- Type Parameters:
K- the type of keys in the map.V- the type of values in the map.- Parameters:
map- the map to make unmodifiable, ornull.- Returns:
- an unmodifiable view or copy of the given map, or
nullif the given map was null. - Since:
- 1.6
- Accepts
-
newCheckedSet
Creates a dynamically type-safe and null-safe set. Any attempt to insert an element of the wrong type will result in an immediateClassCastException, and any attempt to insert a null element will result in an immediateNullPointerException.Differences with standard
This method differs fromCollections.checkedSet(…)methodCollections.checkedSet(Set, Class)in that it copies the given collection instead of wrapping it, verifies the elements of the given collection, does not accept null elements, and returns an instance ofEnumSet,CodeListSetorCheckedContainer.- Type Parameters:
E- the type of collection elements.- Parameters:
collection- the collection to copy in the set, ornullfor creating an initially empty set.elementType- type of elements. This value will be returned byCheckedContainer.getElementType().- Returns:
- a modifiable set initialized to the given collection elements.
- Throws:
NullPointerException- ifelementTypeis null orcollectionis non-null and contains null elements.ClassCastException- if the given collection is non-null and contains elements not assignable toelementType.- Since:
- 1.6
- See Also:
-
newCheckedList
Creates a dynamically type-safe and null-safe list. Any attempt to insert an element of the wrong type will result in an immediateClassCastException, and any attempt to insert a null element will result in an immediateNullPointerException.Differences with standard
This method differs fromCollections.checkedList(…)methodCollections.checkedList(List, Class)in that it copies the given collection instead of wrapping it, verifies the elements of the given collection, does not accept null elements, and returns an instance ofCheckedContainer.- Type Parameters:
E- the type of collection elements.- Parameters:
collection- the collection to copy in the list, ornullfor creating an initially empty list.elementType- type of elements. This value will be returned byCheckedContainer.getElementType().- Returns:
- a modifiable list initialized to the given collection elements.
- Throws:
NullPointerException- ifelementTypeis null orcollectionis non-null and contains null elements.ClassCastException- if the given collection is non-null and contains elements not assignable toelementType.- Since:
- 1.6
- See Also:
-
derivedList
Returns a list whose elements are derived on-the-fly from the given list. Conversions from the original elements to the derived elements are performed when needed by invoking theFunction.apply(Object)method on the given converter. Those conversions are repeated every time that aListmethod needs to access values. Consequently, any change in the original list is immediately visible in the derived list.The returned list can be serialized if the given list and converter are serializable. The returned list is not synchronized by itself, but is nevertheless thread-safe if the given list (including its iterator) and converter are thread-safe.
The returned list does not implement
CheckedContainer.- Type Parameters:
S- the type of elements in the storage (original) list.E- the type of elements in the derived list.- Parameters:
storage- the storage list containing the original elements, ornull.converter- the converter from the elements in the storage list to the elements in the derived list.- Returns:
- a view over the
storagelist containing all elements converted by the given converter, ornullifstoragewas null. - Since:
- 1.6
-
derivedSet
Returns a set whose elements are derived on-the-fly from the given set. Conversions from the original elements to the derived elements are performed when needed by invoking theObjectConverter.apply(Object)method on the given converter. Those conversions are repeated every time that aSetmethod needs to access values. Consequently, any change in the original set is immediately visible in the derived set, and conversely.The
Set.add(E)method is supported only if the given converter is invertible. An invertible converter is not mandatory for otherSetoperations. However,containsandremoveoperations are likely to be faster if the inverse converter is available.The derived set may contain fewer elements than the original set if some elements are not convertible. Non-convertible elements are S values for which
converter.apply(S)returnsnull. As a consequence of this sentinel value usage, the derived set cannot containnullelements.The returned set can be serialized if the given set and converter are serializable. The returned set is not synchronized by itself, but is nevertheless thread-safe if the given set (including its iterator) and converter are thread-safe.
- Type Parameters:
S- the type of elements in the storage (original) set.E- the type of elements in the derived set.- Parameters:
storage- the storage set containing the original elements, ornull.converter- the converter from the elements in the storage set to the elements in the derived set.- Returns:
- a view over the
storageset containing all elements converted by the given converter, ornullifstoragewas null. - See Also:
-
derivedMap
public static <SK,SV, Map<K,K, V> V> derivedMap(Map<SK, SV> storage, ObjectConverter<SK, K> keyConverter, ObjectConverter<SV, V> valueConverter) Returns a map whose keys and values are derived on-the-fly from the given map. Conversions from the original entries to the derived entries are performed when needed by invoking theObjectConverter.apply(Object)method on the given converters. Those conversions are repeated every time that aMapmethod needs to access values. Consequently, any change in the original map is immediately visible in the derived map, and conversely.The
Map.put(K,V)method is supported only if the given converters are invertible. An invertible converter is not mandatory for otherMapoperations likeMap.get(Object), but some of them may be faster if the inverse converters are available.The derived map may contain fewer entries than the original map if some keys are not convertible. A key K is non-convertible if
keyConverter.apply(K)returnsnull. As a consequence of this sentinel key usage, the derived map cannot containnullkeys. It may containnullvalues however.The returned map can be serialized if the given map and converters are serializable. The returned map is not thread-safe.
The returned map does not implement the
CheckedContainerinterface sinceMapis not aCollectionsub-type, but the derived map key set and entry set do.- Type Parameters:
SK- the type of keys in the storage map.SV- the type of values in the storage map.K- the type of keys in the derived map.V- the type of values in the derived map.- Parameters:
storage- the storage map containing the original entries, ornull.keyConverter- the converter from the keys in the storage map to the keys in the derived map.valueConverter- the converter from the values in the storage map to the values in the derived map.- Returns:
- a view over the
storagemap containing all entries converted by the given converters, ornullifstoragewas null. - See Also:
-
toCollection
Returns the given object as a collection. This method recognizes the following types, in that order:- If the object is null, then this method returns an empty set.
- If the object is an instance of
Collection, then it is returned unchanged. - If the object is an array of objects, then it is returned as a list.
- If the object is an array of primitive type, then it is returned as a list of their wrapper class.
- Otherwise, the object is returned as a singleton.
- Parameters:
object- the object to return as a collection, ornull.- Returns:
- the object cast as a collection or wrapped in a collection (never
null). - Since:
- 1.6
-
property
public static <T> T property(Map<?, ?> properties, Object key, Class<T> type) throws IllegalArgumentExceptionReturns the value mapped to the given key cast to the given type, ornullif the map is null or does not contain a value for the key. If the mapped value is non-null but cannot be cast to the given type, then this method throws anIllegalArgumentExceptionwith a message of the formProperty ‘
.key’ does not accept instances of ‘value.class’.This is a helper method for processing a
Mapargument containing property values of various kinds, as in theAbstractIdentifiedObjectconstructor.- Type Parameters:
T- the compile-time value of thetypeargument.- Parameters:
properties- the map of properties from which to get a value, ornullif none.key- the key of the property value to return. Can benullif the map supports null key.type- the expected type of the property value. Cannot be null.- Returns:
- the property value for the given key cast to the given type, or
nullif none. - Throws:
IllegalArgumentException- if a non-null property value exists for the given key but can not be cast to the given type.- See Also:
-
hashMapCapacity
public static int hashMapCapacity(int count) Returns the capacity to give to theHashMapandHashSetconstructors for holding the given number of elements. This method computes the capacity for the default load factor, which is 0.75. This capacity is applicable to the following classes:HashSet,HashMap,LinkedHashSetandLinkedHashMap. This capacity is not applicable toIdentityHashMap.Since Java 19, the static factory methods in above-cited classes should be used instead of this method. However, this
hashMapCapacitymethod is still useful in a few cases where the standard factory methods cannot be invoked, for example because the collection to construct is a subclasses for the standard classes.- Parameters:
count- the number of elements to be put into the hash map or hash set.- Returns:
- the minimal initial capacity to be given to the hash map constructor.
-
compare
Compares element-by-element the values provided by two iterators, in iteration order. Leto1be an element from the first iterator ando2the element at the same position from the second iterator. This method returns the result of the firsto1.compareTo(o2)call which returned a value different than zero. If allo1.compareTo(o2)calls returned zero, then this method returns -1 ifit1iteration finished beforeit2, +1 ifit2iteration finished beforeit1, or 0 if both iterators finished at the same time.Iterators may return null elements. Null elements are considered "after" any non-null element.
- Type Parameters:
E- the type of elements returned by the iterators.- Parameters:
it1- the first iterator (cannot be null).it2- the second iterator (cannot be null).- Returns:
- -1 if the content given by the first iterator is considered "before" the content given by the second iterator, +1 if considered "after", or 0 if considered equal.
- Since:
- 1.0
-
viewAsUnmodifiableList(Object...)for clarity.