Class CollectionUtilities
CollectionUtilities
simplifies tasks such as null-safe checks, retrieving collection sizes,
creating immutable collections, and wrapping collections in checked, synchronized, or unmodifiable views.
It includes functionality compatible with JDK 8, providing alternatives to methods introduced in later
versions of Java, such as
invalid reference
java.util.List#of(Object...)
invalid reference
java.util.Set#of(Object...)
Key Features
- Null-Safe Checks:
isEmpty(Collection)
: Checks if a collection is null or empty.hasContent(Collection)
: Checks if a collection is not null and contains at least one element.size(Collection)
: Safely retrieves the size of a collection, returning0
if it is null.
- Immutable Collection Creation:
listOf(Object...)
: Creates an immutable list of specified elements, compatible with JDK 8.setOf(Object...)
: Creates an immutable set of specified elements, compatible with JDK 8.
- Collection Wrappers:
getUnmodifiableCollection(Collection)
: Wraps a collection in the most specific unmodifiable view based on its type (e.g.,NavigableSet
,SortedSet
,List
).getCheckedCollection(Collection, Class)
: Wraps a collection in the most specific type-safe checked view based on its type (e.g.,NavigableSet
,SortedSet
,List
).getSynchronizedCollection(Collection)
: Wraps a collection in the most specific thread-safe synchronized view based on its type (e.g.,NavigableSet
,SortedSet
,List
).getEmptyCollection(Collection)
: Returns an empty collection of the same type as the input collection (e.g.,NavigableSet
,SortedSet
,List
).
Usage Examples
// Null-safe checks
boolean isEmpty = CollectionUtilities.isEmpty(myCollection);
boolean hasContent = CollectionUtilities.hasContent(myCollection);
int size = CollectionUtilities.size(myCollection);
// Immutable collections
List<String> list = CollectionUtilities.listOf("A", "B", "C");
Set<String> set = CollectionUtilities.setOf("X", "Y", "Z");
// Collection wrappers
Collection<?> unmodifiable = CollectionUtilities.getUnmodifiableCollection(myCollection);
Collection<?> checked = CollectionUtilities.getCheckedCollection(myCollection, String.class);
Collection<?> synchronizedCollection = CollectionUtilities.getSynchronizedCollection(myCollection);
Collection<?> empty = CollectionUtilities.getEmptyCollection(myCollection);
Design Notes
- This class is designed as a static utility class and should not be instantiated.
- It uses unmodifiable empty collections as constants to optimize memory usage and prevent unnecessary object creation.
- The collection wrappers apply type-specific operations based on the runtime type of the provided collection.
- Author:
- John DeRegnaucourt ([email protected])
Copyright (c) Cedar Software LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
License
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T extends Collection<?>,
E>
Collection<E> getCheckedCollection
(T collection, Class<E> type) Wraps the provided collection in a checked wrapper that enforces type safety.static <T> Collection
<T> getEmptyCollection
(Collection<T> collection) Returns an empty collection of the same type as the provided collection.static <T> Collection
<T> getSynchronizedCollection
(Collection<T> collection) Wraps the provided collection in a thread-safe synchronized wrapper.static <T> Collection
<T> getUnmodifiableCollection
(Collection<T> collection) Wraps the provided collection in an unmodifiable wrapper appropriate to its runtime type.static boolean
hasContent
(Collection<?> col) Checks if the specified collection is notnull
and contains at least one element.static boolean
isEmpty
(Collection<?> col) This is a null-safe isEmpty check.static boolean
isSynchronized
(Class<?> targetType) Determines whether the specified class represents an synchronized collection type.static boolean
isUnmodifiable
(Class<?> targetType) Determines whether the specified class represents an unmodifiable collection type.static <T> List
<T> listOf
(T... items) Creates an unmodifiable list containing the specified elements.static <T> Set
<T> setOf
(T... items) Creates an unmodifiable set containing the specified elements.static int
size
(Collection<?> col) Returns the size of the specified collection in a null-safe manner.
-
Method Details
-
isEmpty
This is a null-safe isEmpty check.- Parameters:
col
- the collection to check, may benull
- Returns:
true
if the collection isnull
or empty;false
otherwise
-
hasContent
Checks if the specified collection is notnull
and contains at least one element.This method provides a null-safe way to verify that a collection has content, returning
false
if the collection isnull
or empty.- Parameters:
col
- the collection to check, may benull
- Returns:
true
if the collection is notnull
and contains at least one element;false
otherwise
-
size
Returns the size of the specified collection in a null-safe manner.If the collection is
null
, this method returns0
. Otherwise, it returns the number of elements in the collection.- Parameters:
col
- the collection to check, may benull
- Returns:
- the size of the collection, or
0
if the collection isnull
-
listOf
Creates an unmodifiable list containing the specified elements.This method provides functionality similar to
invalid reference
java.util.List#of(Object...)
null
or empty, this method returns an unmodifiable empty list.Usage Example
List<String> list = listOf("A", "B", "C"); // Returns an unmodifiable list containing "A", "B", "C" List<String> emptyList = listOf(); // Returns an unmodifiable empty list
- Type Parameters:
T
- the type of elements in the list- Parameters:
items
- the elements to be included in the list; may benull
- Returns:
- an unmodifiable list containing the specified elements, or an unmodifiable empty list if the input is
null
or empty - Throws:
NullPointerException
- if any of the elements in the input array arenull
- See Also:
-
setOf
Creates an unmodifiable set containing the specified elements.This method provides functionality similar to
invalid reference
java.util.Set#of(Object...)
null
or empty, this method returns an unmodifiable empty set.Usage Example
Set<String> set = setOf("A", "B", "C"); // Returns an unmodifiable set containing "A", "B", "C" Set<String> emptySet = setOf(); // Returns an unmodifiable empty set
- Type Parameters:
T
- the type of elements in the set- Parameters:
items
- the elements to be included in the set; may benull
- Returns:
- an unmodifiable set containing the specified elements, or an unmodifiable empty set if the input is
null
or empty - Throws:
NullPointerException
- if any of the elements in the input array arenull
- See Also:
-
isUnmodifiable
Determines whether the specified class represents an unmodifiable collection type.This method checks if the provided
targetType
is assignable to the class of unmodifiable collections. It is commonly used to identify whether a given class type indicates a collection that cannot be modified (e.g., collections wrapped withCollections.unmodifiableCollection(Collection)
or its specialized variants).Null Handling: If
targetType
isnull
, this method will throw aNullPointerException
with a clear error message.- Parameters:
targetType
- theClass
to check, must not benull
- Returns:
true
if the specifiedtargetType
indicates an unmodifiable collection;false
otherwise- Throws:
NullPointerException
- iftargetType
isnull
- See Also:
-
isSynchronized
Determines whether the specified class represents an synchronized collection type.This method checks if the provided
targetType
is assignable to the class of synchronized collections. It is commonly used to identify whether a given class type indicates a collection that supports concurrent access (e.g., collections wrapped withCollections.synchronizedCollection(Collection)
or its specialized variants).Null Handling: If
targetType
isnull
, this method will throw aNullPointerException
with a clear error message.- Parameters:
targetType
- theClass
to check, must not benull
- Returns:
true
if the specifiedtargetType
indicates a synchronized collection;false
otherwise- Throws:
NullPointerException
- iftargetType
isnull
- See Also:
-
getUnmodifiableCollection
Wraps the provided collection in an unmodifiable wrapper appropriate to its runtime type.This method ensures that the collection cannot be modified by any client code and applies the most specific unmodifiable wrapper based on the runtime type of the provided collection:
- If the collection is a
NavigableSet
, it is wrapped usingCollections.unmodifiableNavigableSet(NavigableSet)
. - If the collection is a
SortedSet
, it is wrapped usingCollections.unmodifiableSortedSet(SortedSet)
. - If the collection is a
Set
, it is wrapped usingCollections.unmodifiableSet(Set)
. - If the collection is a
List
, it is wrapped usingCollections.unmodifiableList(List)
. - Otherwise, it is wrapped using
Collections.unmodifiableCollection(Collection)
.
Attempting to modify the returned collection will result in an
UnsupportedOperationException
at runtime. For example:NavigableSet<String> set = new TreeSet<>(Set.of("A", "B", "C")); NavigableSet<String> unmodifiableSet = (NavigableSet<String>) getUnmodifiableCollection(set); unmodifiableSet.add("D"); // Throws UnsupportedOperationException
Null Handling
If the input collection is
null
, this method will throw aNullPointerException
with a descriptive error message.- Type Parameters:
T
- the type of elements in the collection- Parameters:
collection
- the collection to be wrapped in an unmodifiable wrapper- Returns:
- an unmodifiable view of the provided collection, preserving its runtime type
- Throws:
NullPointerException
- if the provided collection isnull
- See Also:
- If the collection is a
-
getEmptyCollection
Returns an empty collection of the same type as the provided collection.This method determines the runtime type of the input collection and returns an appropriate empty collection instance:
- If the collection is a
NavigableSet
, it returnsCollections.emptyNavigableSet()
. - If the collection is a
SortedSet
, it returnsCollections.emptySortedSet()
. - If the collection is a
Set
, it returnsCollections.emptySet()
. - If the collection is a
List
, it returnsCollections.emptyList()
. - For all other collection types, it defaults to returning
Collections.emptyList()
.
The returned collection is immutable and will throw an
UnsupportedOperationException
if any modification is attempted. For example:List<String> list = new ArrayList<>(); Collection<String> emptyList = getEmptyCollection(list); emptyList.add("one"); // Throws UnsupportedOperationException
Null Handling
If the input collection is
null
, this method will throw aNullPointerException
with a descriptive error message.Usage Notes
- The returned collection is type-specific based on the input collection, ensuring compatibility with type-specific operations such as iteration or ordering.
- The method provides an empty collection that is appropriate for APIs requiring non-null collections as inputs or defaults.
- Type Parameters:
T
- the type of elements in the collection- Parameters:
collection
- the collection whose type determines the type of the returned empty collection- Returns:
- an empty, immutable collection of the same type as the input collection
- Throws:
NullPointerException
- if the provided collection isnull
- See Also:
- If the collection is a
-
getCheckedCollection
public static <T extends Collection<?>,E> Collection<E> getCheckedCollection(T collection, Class<E> type) Wraps the provided collection in a checked wrapper that enforces type safety.This method applies the most specific checked wrapper based on the runtime type of the collection:
- If the collection is a
NavigableSet
, it is wrapped usingCollections.checkedNavigableSet(NavigableSet, Class)
. - If the collection is a
SortedSet
, it is wrapped usingCollections.checkedSortedSet(SortedSet, Class)
. - If the collection is a
Set
, it is wrapped usingCollections.checkedSet(Set, Class)
. - If the collection is a
List
, it is wrapped usingCollections.checkedList(List, Class)
. - Otherwise, it is wrapped using
Collections.checkedCollection(Collection, Class)
.
Attempting to add an element to the returned collection that is not of the specified type will result in a
ClassCastException
at runtime. For example:List<Object> list = new ArrayList<>(List.of("one", "two")); Collection<String> checkedCollection = getCheckedCollection(list, String.class); // Adding a String is allowed checkedCollection.add("three"); // Adding an Integer will throw a ClassCastException checkedCollection.add(42); // Throws ClassCastException
Null Handling
If the input collection or the type class is
null
, this method will throw aNullPointerException
with a descriptive error message.Usage Notes
- The method enforces runtime type safety by validating all elements added to the collection.
- The returned collection retains the original type-specific behavior of the input collection
(e.g., sorting for
SortedSet
or ordering forList
). - Use this method when you need to ensure that a collection only contains elements of a specific type.
- Type Parameters:
T
- the type of the input collectionE
- the type of elements in the collection- Parameters:
collection
- the collection to be wrapped, must not benull
type
- the class of elements that the collection is permitted to hold, must not benull
- Returns:
- a checked view of the provided collection
- Throws:
NullPointerException
- if the provided collection or type isnull
- See Also:
- If the collection is a
-
getSynchronizedCollection
Wraps the provided collection in a thread-safe synchronized wrapper.This method applies the most specific synchronized wrapper based on the runtime type of the collection:
- If the collection is a
NavigableSet
, it is wrapped usingCollections.synchronizedNavigableSet(NavigableSet)
. - If the collection is a
SortedSet
, it is wrapped usingCollections.synchronizedSortedSet(SortedSet)
. - If the collection is a
Set
, it is wrapped usingCollections.synchronizedSet(Set)
. - If the collection is a
List
, it is wrapped usingCollections.synchronizedList(List)
. - Otherwise, it is wrapped using
Collections.synchronizedCollection(Collection)
.
The returned collection is thread-safe. However, iteration over the collection must be manually synchronized:
List<String> list = new ArrayList<>(List.of("one", "two", "three")); Collection<String> synchronizedList = getSynchronizedCollection(list); synchronized (synchronizedList) { for (String item : synchronizedList) { System.out.println(item); } }
Null Handling
If the input collection is
null
, this method will throw aNullPointerException
with a descriptive error message.Usage Notes
- The method returns a synchronized wrapper that delegates all operations to the original collection.
- Any structural modifications (e.g.,
add
,remove
) must occur within a synchronized block to ensure thread safety during concurrent access.
- Type Parameters:
T
- the type of elements in the collection- Parameters:
collection
- the collection to be wrapped in a synchronized wrapper- Returns:
- a synchronized view of the provided collection, preserving its runtime type
- Throws:
NullPointerException
- if the provided collection isnull
- See Also:
- If the collection is a
-