Class CollectionUtilities

java.lang.Object
com.cedarsoftware.util.CollectionUtilities

public class CollectionUtilities extends Object
A utility class providing enhanced operations for working with Java collections.

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...)
and
invalid reference
java.util.Set#of(Object...)
.

Key Features

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 Details

    • isEmpty

      public static boolean isEmpty(Collection<?> col)
      This is a null-safe isEmpty check.
      Parameters:
      col - the collection to check, may be null
      Returns:
      true if the collection is null or empty; false otherwise
    • hasContent

      public static boolean hasContent(Collection<?> col)
      Checks if the specified collection is not null 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 is null or empty.

      Parameters:
      col - the collection to check, may be null
      Returns:
      true if the collection is not null and contains at least one element; false otherwise
    • size

      public static int size(Collection<?> col)
      Returns the size of the specified collection in a null-safe manner.

      If the collection is null, this method returns 0. Otherwise, it returns the number of elements in the collection.

      Parameters:
      col - the collection to check, may be null
      Returns:
      the size of the collection, or 0 if the collection is null
    • listOf

      @SafeVarargs public static <T> List<T> listOf(T... items)
      Creates an unmodifiable list containing the specified elements.

      This method provides functionality similar to

      invalid reference
      java.util.List#of(Object...)
      introduced in JDK 9, but is compatible with JDK 8. If the input array is 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 be null
      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 are null
      See Also:
    • setOf

      @SafeVarargs public static <T> Set<T> setOf(T... items)
      Creates an unmodifiable set containing the specified elements.

      This method provides functionality similar to

      invalid reference
      java.util.Set#of(Object...)
      introduced in JDK 9, but is compatible with JDK 8. If the input array is 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 be null
      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 are null
      See Also:
    • isUnmodifiable

      public static boolean isUnmodifiable(Class<?> targetType)
      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 with Collections.unmodifiableCollection(Collection) or its specialized variants).

      Null Handling: If targetType is null, this method will throw a NullPointerException with a clear error message.

      Parameters:
      targetType - the Class to check, must not be null
      Returns:
      true if the specified targetType indicates an unmodifiable collection; false otherwise
      Throws:
      NullPointerException - if targetType is null
      See Also:
    • isSynchronized

      public static boolean isSynchronized(Class<?> targetType)
      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 with Collections.synchronizedCollection(Collection) or its specialized variants).

      Null Handling: If targetType is null, this method will throw a NullPointerException with a clear error message.

      Parameters:
      targetType - the Class to check, must not be null
      Returns:
      true if the specified targetType indicates a synchronized collection; false otherwise
      Throws:
      NullPointerException - if targetType is null
      See Also:
    • getUnmodifiableCollection

      public static <T> Collection<T> getUnmodifiableCollection(Collection<T> collection)
      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:

      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 a NullPointerException 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 is null
      See Also:
    • getEmptyCollection

      public static <T> Collection<T> getEmptyCollection(Collection<T> collection)
      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:

      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 a NullPointerException 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 is null
      See Also:
    • 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:

      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 a NullPointerException 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 for List).
      • 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 collection
      E - the type of elements in the collection
      Parameters:
      collection - the collection to be wrapped, must not be null
      type - the class of elements that the collection is permitted to hold, must not be null
      Returns:
      a checked view of the provided collection
      Throws:
      NullPointerException - if the provided collection or type is null
      See Also:
    • getSynchronizedCollection

      public static <T> Collection<T> getSynchronizedCollection(Collection<T> collection)
      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:

      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 a NullPointerException 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 is null
      See Also: