CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-apache-commons--commons-collections4

The Apache Commons Collections package contains types that extend and augment the Java Collections Framework

Pending
Overview
Eval results
Files

collection-utilities.mddocs/

Collection Utilities

Apache Commons Collections provides extensive utility classes with static methods for common collection operations. These utilities offer null-safe operations, set theory functions, transformations, and decorators for all major collection types.

CollectionUtils - Core Collection Operations

Basic Operations and Null Safety

import org.apache.commons.collections4.CollectionUtils;
import java.util.List;
import java.util.Arrays;
import java.util.Collection;
import java.util.ArrayList;

// Null-safe operations
boolean isEmpty = CollectionUtils.isEmpty(null);           // true
boolean isNotEmpty = CollectionUtils.isNotEmpty(null);     // false

List<String> emptyList = new ArrayList<>();
boolean empty = CollectionUtils.isEmpty(emptyList);        // true

List<String> items = Arrays.asList("a", "b", "c");
boolean notEmpty = CollectionUtils.isNotEmpty(items);      // true

// Safe size operations
int size = CollectionUtils.size(null);                     // 0
int actualSize = CollectionUtils.size(items);              // 3

// Safe addition (ignores null elements)
Collection<String> collection = new ArrayList<>();
CollectionUtils.addIgnoreNull(collection, "item");        // Added
CollectionUtils.addIgnoreNull(collection, null);          // Ignored

// Add multiple elements safely
String[] elements = {"a", "b", "c"};
CollectionUtils.addAll(collection, elements);

Set Theory Operations

List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(4, 5, 6, 7, 8);

// Union (all unique elements from both collections)
Collection<Integer> union = CollectionUtils.union(list1, list2);
// Result: [1, 2, 3, 4, 5, 6, 7, 8]

// Intersection (common elements)  
Collection<Integer> intersection = CollectionUtils.intersection(list1, list2);
// Result: [4, 5]

// Disjunction (elements in either collection but not both)
Collection<Integer> disjunction = CollectionUtils.disjunction(list1, list2);
// Result: [1, 2, 3, 6, 7, 8]

// Subtract (elements in first collection but not in second)
Collection<Integer> difference = CollectionUtils.subtract(list1, list2);
// Result: [1, 2, 3]

// Cardinality (count occurrences of element)
List<String> words = Arrays.asList("apple", "banana", "apple", "cherry", "apple");
int appleCount = CollectionUtils.cardinality("apple", words);  // 3
int orangeCount = CollectionUtils.cardinality("orange", words); // 0

Filtering and Selection

import org.apache.commons.collections4.Predicate;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Select elements matching predicate
Predicate<Integer> evenPredicate = n -> n % 2 == 0;
Collection<Integer> evenNumbers = CollectionUtils.select(numbers, evenPredicate);
// Result: [2, 4, 6, 8, 10]

// Reject elements matching predicate (opposite of select)
Collection<Integer> oddNumbers = CollectionUtils.selectRejected(numbers, evenPredicate);
// Result: [1, 3, 5, 7, 9]

// Find first element matching predicate
Integer firstEven = CollectionUtils.find(numbers, evenPredicate);  // 2

// Check if any element matches predicate
boolean hasEven = CollectionUtils.exists(numbers, evenPredicate);  // true

// Count matching elements
int evenCount = CollectionUtils.countMatches(numbers, evenPredicate); // 5

// Complex predicates
Predicate<Integer> largeEven = n -> n % 2 == 0 && n > 5;
Collection<Integer> largeEvens = CollectionUtils.select(numbers, largeEven);
// Result: [6, 8, 10]

Transformations

import org.apache.commons.collections4.Transformer;

List<String> words = Arrays.asList("hello", "world", "java", "collections");

// Transform collection elements
Transformer<String, String> upperCase = String::toUpperCase;
Collection<String> upperWords = CollectionUtils.collect(words, upperCase);
// Result: ["HELLO", "WORLD", "JAVA", "COLLECTIONS"]

Transformer<String, Integer> stringLength = String::length;
Collection<Integer> wordLengths = CollectionUtils.collect(words, stringLength);
// Result: [5, 5, 4, 11]

// Transform and add to existing collection
Collection<String> result = new ArrayList<>();
CollectionUtils.collect(words, upperCase, result);
// result now contains uppercase words

// Chain transformations
Transformer<String, String> trimUpper = s -> s.trim().toUpperCase();
Collection<String> processed = CollectionUtils.collect(
    Arrays.asList("  hello  ", " world ", "  java  "),
    trimUpper
);
// Result: ["HELLO", "WORLD", "JAVA"]

Equality and Comparison

List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("c", "b", "a");
List<String> list3 = Arrays.asList("a", "b", "c");

// Equal collections (same elements, same cardinalities, order doesn't matter)
boolean equal1 = CollectionUtils.isEqualCollection(list1, list2); // true
boolean equal2 = CollectionUtils.isEqualCollection(list1, list3); // true

// Check if collection is a sub-collection
List<String> subset = Arrays.asList("a", "b");
boolean isSubCollection = CollectionUtils.isSubCollection(subset, list1); // true

// Check if collection is a proper sub-collection (subset but not equal)
boolean isProperSubCollection = CollectionUtils.isProperSubCollection(subset, list1); // true
boolean isProperSelf = CollectionUtils.isProperSubCollection(list1, list1); // false

ListUtils - List-Specific Operations

List Set Operations

import org.apache.commons.collections4.ListUtils;

List<String> list1 = Arrays.asList("a", "b", "c", "d");
List<String> list2 = Arrays.asList("c", "d", "e", "f");

// Union preserving order and duplicates
List<String> union = ListUtils.union(list1, list2);
// Result: ["a", "b", "c", "d", "c", "d", "e", "f"]

// Intersection preserving order
List<String> intersection = ListUtils.intersection(list1, list2);
// Result: ["c", "d"]

// Subtract (elements in first but not in second)
List<String> subtract = ListUtils.subtract(list1, list2);
// Result: ["a", "b"]

// Sum (concatenation)
List<String> sum = ListUtils.sum(list1, list2);
// Result: ["a", "b", "c", "d", "c", "d", "e", "f"]

List Equality and Manipulation

List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(1, 2, 3, 4);
List<Integer> list3 = Arrays.asList(4, 3, 2, 1);

// Order-sensitive equality (unlike CollectionUtils.isEqualCollection)
boolean equalLists = ListUtils.isEqualList(list1, list2);     // true
boolean differentOrder = ListUtils.isEqualList(list1, list3); // false

// Hash code for lists
int hashCode1 = ListUtils.hashCodeForList(list1);
int hashCode2 = ListUtils.hashCodeForList(list2); // Same as hashCode1

// Retain elements (intersection that modifies original collection concept)
List<Integer> toRetain = Arrays.asList(2, 3, 5, 6);
List<Integer> retained = ListUtils.retainAll(list1, toRetain);
// Result: [2, 3] (elements from list1 that are also in toRetain)

// Remove elements
List<Integer> toRemove = Arrays.asList(2, 4);
List<Integer> remaining = ListUtils.removeAll(list1, toRemove);
// Result: [1, 3] (elements from list1 not in toRemove)

List Partitioning

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Partition into sublists of specified size
List<List<Integer>> partitions = ListUtils.partition(numbers, 3);
// Result: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

// Process partitions
for (List<Integer> partition : partitions) {
    System.out.println("Partition sum: " + partition.stream().mapToInt(Integer::intValue).sum());
}

// Useful for batch processing
List<String> largeList = generateLargeList(); // Imagine 10,000 items
List<List<String>> batches = ListUtils.partition(largeList, 100);
for (List<String> batch : batches) {
    processBatch(batch); // Process 100 items at a time
}

List Decorators

import java.util.ArrayList;

List<String> baseList = new ArrayList<>();
baseList.addAll(Arrays.asList("a", "b", "c"));

// Synchronized list
List<String> syncList = ListUtils.synchronizedList(baseList);

// Unmodifiable list
List<String> readOnlyList = ListUtils.unmodifiableList(baseList);

// Predicated list (validates additions)
Predicate<String> notEmpty = s -> s != null && !s.trim().isEmpty();
List<String> validatedList = ListUtils.predicatedList(new ArrayList<>(), notEmpty);
validatedList.add("valid");  // OK
// validatedList.add(""); // Would throw IllegalArgumentException

// Transformed list (transforms elements on addition)
Transformer<String, String> upperCase = String::toUpperCase;
List<String> transformedList = ListUtils.transformedList(new ArrayList<>(), upperCase);
transformedList.add("hello"); // Stored as "HELLO"

// Lazy list (creates elements on demand)
Factory<String> defaultFactory = () -> "default";
List<String> lazyList = ListUtils.lazyList(new ArrayList<>(), defaultFactory);
String item = lazyList.get(5); // Creates elements 0-5 with "default" value

// Fixed size list (prevents size changes)
List<String> fixedList = ListUtils.fixedSizeList(new ArrayList<>(Arrays.asList("a", "b", "c")));
fixedList.set(0, "changed"); // OK - modification allowed
// fixedList.add("new"); // Would throw UnsupportedOperationException

SetUtils - Set-Specific Operations

Set Operations with Views

import org.apache.commons.collections4.SetUtils;
import java.util.Set;
import java.util.HashSet;

Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c", "d"));
Set<String> set2 = new HashSet<>(Arrays.asList("c", "d", "e", "f"));

// Immutable set views (don't copy data, just provide views)
SetUtils.SetView<String> unionView = SetUtils.union(set1, set2);
// View contains: ["a", "b", "c", "d", "e", "f"]

SetUtils.SetView<String> intersectionView = SetUtils.intersection(set1, set2);
// View contains: ["c", "d"]

SetUtils.SetView<String> differenceView = SetUtils.difference(set1, set2);
// View contains: ["a", "b"] (in set1 but not set2)

SetUtils.SetView<String> disjunctionView = SetUtils.disjunction(set1, set2);
// View contains: ["a", "b", "e", "f"] (in either set but not both)

// Views are live - changes to original sets are reflected
set1.add("x");
System.out.println(unionView.contains("x")); // true

// Convert view to concrete set when needed
Set<String> concreteUnion = new HashSet<>(unionView);

Set Equality and Validation

Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 2, 1)); // Different order
List<Integer> list = Arrays.asList(1, 2, 3, 2); // With duplicate

// Set equality (order doesn't matter)
boolean equal = SetUtils.isEqualSet(set1, set2); // true

// Check if collection represents a valid set (no duplicates)
boolean validSet1 = SetUtils.isEqualSet(set1, list); // false (list has duplicate)

// Hash code for sets
int hashCode = SetUtils.hashCodeForSet(set1);

Set Decorators

Set<String> baseSet = new HashSet<>();

// Synchronized set
Set<String> syncSet = SetUtils.synchronizedSet(baseSet);

// Unmodifiable set
Set<String> readOnlySet = SetUtils.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));

// Predicated set
Predicate<String> notNull = Objects::nonNull;
Set<String> validatedSet = SetUtils.predicatedSet(new HashSet<>(), notNull);

// Transformed set
Transformer<String, String> lowerCase = String::toLowerCase;
Set<String> transformedSet = SetUtils.transformedSet(new HashSet<>(), lowerCase);
transformedSet.add("HELLO"); // Stored as "hello"

// Empty immutable set
Set<String> empty = SetUtils.emptySet(); // Singleton empty set

MapUtils - Map Operations

Basic Map Operations

import org.apache.commons.collections4.MapUtils;
import java.util.Map;
import java.util.HashMap;

Map<String, Integer> map = new HashMap<>();
map.put("apple", 5);
map.put("banana", 3);
map.put("cherry", 8);

// Null-safe operations
boolean isEmpty = MapUtils.isEmpty(null);           // true
boolean isNotEmpty = MapUtils.isNotEmpty(map);      // true

// Safe value retrieval with defaults
Integer value = MapUtils.getInteger(map, "apple");      // 5
Integer missing = MapUtils.getInteger(map, "orange");   // null
Integer withDefault = MapUtils.getInteger(map, "orange", 0); // 0

// Type-safe getters
String stringValue = MapUtils.getString(map, "apple");   // "5" (converted)
Boolean boolValue = MapUtils.getBoolean(map, "apple");   // true (5 -> true)
Double doubleValue = MapUtils.getDouble(map, "apple");   // 5.0

// Safe addition (ignores if key or value is problematic)
MapUtils.safeAddToMap(map, "date", new Date());

Map Inversion and Debugging

Map<String, Integer> original = Map.of("a", 1, "b", 2, "c", 3);

// Invert key-value pairs (assumes values are unique)
Map<Integer, String> inverted = MapUtils.invertMap(original);
// Result: {1="a", 2="b", 3="c"}

// Debug printing
MapUtils.debugPrint(System.out, "Original Map", original);
// Prints formatted key-value pairs for debugging

MapUtils.verbosePrint(System.out, "Detailed Map", original);
// Prints with more detailed formatting

Map Decorators

Map<String, String> baseMap = new HashMap<>();

// Synchronized map
Map<String, String> syncMap = MapUtils.synchronizedMap(baseMap);

// Unmodifiable map
Map<String, String> readOnlyMap = MapUtils.unmodifiableMap(
    Map.of("key1", "value1", "key2", "value2")
);

// Predicated map (validates keys and values)
Predicate<String> notEmpty = s -> s != null && !s.trim().isEmpty();
IterableMap<String, String> validatedMap = MapUtils.predicatedMap(
    new HashMap<>(),
    notEmpty,  // Key predicate  
    notEmpty   // Value predicate
);

// Transformed map
Transformer<String, String> keyUpper = String::toUpperCase;
Transformer<String, String> valueUpper = String::toUpperCase;
IterableMap<String, String> transformedMap = MapUtils.transformedMap(
    new HashMap<>(),
    keyUpper,    // Key transformer
    valueUpper   // Value transformer  
);

// Lazy map (creates values on first access)
Factory<List<String>> listFactory = ArrayList::new;
IterableMap<String, List<String>> lazyMap = MapUtils.lazyMap(new HashMap<>(), listFactory);
lazyMap.get("key1").add("value"); // Creates ArrayList automatically

// Fixed size map (prevents adding new entries)
IterableMap<String, String> fixedMap = MapUtils.fixedSizeMap(
    new HashMap<>(Map.of("existing", "value"))
);

Advanced Utility Patterns

Fluent Processing Chains

import org.apache.commons.collections4.FluentIterable;

List<String> input = Arrays.asList("  hello  ", "", "WORLD", "  java  ", null, "collections");

// Chain operations fluently
List<String> processed = FluentIterable.of(input)
    .filter(Objects::nonNull)                          // Remove nulls
    .filter(s -> !s.trim().isEmpty())                  // Remove empty strings
    .transform(String::trim)                           // Trim whitespace
    .transform(String::toLowerCase)                    // Convert to lowercase  
    .filter(s -> s.length() > 3)                      // Keep only longer words
    .toList();
// Result: ["hello", "world", "java", "collections"]

// Check conditions on entire collection
boolean allLongWords = FluentIterable.of(processed)
    .allMatch(s -> s.length() > 2);                    // true

boolean anyStartsWithJ = FluentIterable.of(processed)  
    .anyMatch(s -> s.startsWith("j"));                 // true

// Limit and skip operations
List<String> limited = FluentIterable.of(processed)
    .skip(1)                                          // Skip first element
    .limit(2)                                         // Take next 2 elements
    .toList();
// Result: ["world", "java"]

Collection Pipeline Factory

public class CollectionPipeline {
    public static <T> Builder<T> from(Collection<T> source) {
        return new Builder<>(source);
    }
    
    public static class Builder<T> {
        private Collection<T> current;
        
        public Builder(Collection<T> source) {
            this.current = new ArrayList<>(source);
        }
        
        public Builder<T> filter(Predicate<T> predicate) {
            current = CollectionUtils.select(current, predicate);
            return this;
        }
        
        public <R> Builder<R> transform(Transformer<T, R> transformer) {
            Collection<R> transformed = CollectionUtils.collect(current, transformer);
            return new Builder<>(transformed);
        }
        
        public Builder<T> unique() {
            current = new ArrayList<>(new LinkedHashSet<>(current));
            return this;
        }
        
        public List<T> toList() {
            return new ArrayList<>(current);
        }
        
        public Set<T> toSet() {
            return new HashSet<>(current);
        }
    }
    
    // Usage example
    public static void example() {
        List<String> words = Arrays.asList("hello", "world", "hello", "java", "world");
        
        List<String> processed = CollectionPipeline.from(words)
            .filter(s -> s.length() > 4)           // Only words longer than 4 chars
            .transform(String::toUpperCase)        // Convert to uppercase
            .unique()                              // Remove duplicates
            .toList();
        // Result: ["HELLO", "WORLD"]
    }
}

Null-Safe Collection Operations

public class SafeCollectionUtils {
    
    public static <T> Collection<T> safeUnion(Collection<T> a, Collection<T> b) {
        if (CollectionUtils.isEmpty(a)) return b == null ? Collections.emptyList() : new ArrayList<>(b);
        if (CollectionUtils.isEmpty(b)) return new ArrayList<>(a);
        return CollectionUtils.union(a, b);
    }
    
    public static <T> boolean safeContains(Collection<T> collection, T item) {
        return CollectionUtils.isNotEmpty(collection) && collection.contains(item);
    }
    
    public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
        if (CollectionUtils.isEmpty(list)) return Collections.emptyList();
        int size = list.size();
        int safeFrom = Math.max(0, Math.min(fromIndex, size));
        int safeTo = Math.max(safeFrom, Math.min(toIndex, size));
        return list.subList(safeFrom, safeTo);
    }
    
    public static <T> T safeGet(List<T> list, int index, T defaultValue) {
        if (CollectionUtils.isEmpty(list) || index < 0 || index >= list.size()) {
            return defaultValue;
        }
        return list.get(index);
    }
}

Performance-Optimized Utilities

public class PerformanceUtils {
    
    // Efficient membership testing for large collections
    public static <T> Predicate<T> createMembershipPredicate(Collection<T> collection) {
        if (CollectionUtils.isEmpty(collection)) {
            return t -> false;
        }
        
        // Use Set for O(1) lookup if not already a Set
        Set<T> lookupSet = collection instanceof Set 
            ? (Set<T>) collection 
            : new HashSet<>(collection);
            
        return lookupSet::contains;
    }
    
    // Batch process large collections to avoid memory issues
    public static <T> void processBatches(Collection<T> items, int batchSize, 
                                         Consumer<List<T>> batchProcessor) {
        if (CollectionUtils.isEmpty(items)) return;
        
        List<T> itemList = items instanceof List 
            ? (List<T>) items 
            : new ArrayList<>(items);
            
        List<List<T>> batches = ListUtils.partition(itemList, batchSize);
        batches.forEach(batchProcessor);
    }
    
    // Efficient filtering for large collections
    public static <T> Collection<T> efficientFilter(Collection<T> source, Predicate<T> predicate) {
        if (CollectionUtils.isEmpty(source)) return Collections.emptyList();
        
        // Pre-size collection for efficiency
        Collection<T> result = new ArrayList<>(source.size() / 4); // Assume 25% pass filter
        
        for (T item : source) {
            if (predicate.evaluate(item)) {
                result.add(item);
            }
        }
        
        return result;
    }
}

Best Practices

Choosing the Right Utility Method

// For null safety, always prefer Commons Collections utilities
Collection<String> safe = CollectionUtils.emptyIfNull(possiblyNullCollection);
int size = CollectionUtils.size(possiblyNullCollection); // Returns 0 if null

// For performance-critical operations, consider the collection type
Set<String> set = new HashSet<>();
List<String> list = new ArrayList<>();

// Fast for Set, slower for List
boolean inSet = set.contains("item");    // O(1) average
boolean inList = list.contains("item");  // O(n)

// Use appropriate set operations
Collection<String> intersection = CollectionUtils.intersection(set, list); // Efficient

Memory and Performance Considerations

// Memory-efficient operations
List<String> huge = getHugeList(); // 1M items

// Memory efficient - doesn't create intermediate collections
long count = huge.stream().filter(s -> s.startsWith("prefix")).count();

// Less memory efficient - creates filtered collection
Collection<String> filtered = CollectionUtils.select(huge, s -> s.startsWith("prefix"));

// For repeated operations, create reusable predicates
Predicate<String> startsWithPrefix = s -> s.startsWith("prefix");
Collection<String> filtered1 = CollectionUtils.select(collection1, startsWithPrefix);
Collection<String> filtered2 = CollectionUtils.select(collection2, startsWithPrefix);

IteratorUtils - Iterator Operations

Comprehensive utilities for working with iterators, providing creation, transformation, and manipulation methods.

import org.apache.commons.collections4.IteratorUtils;
import java.util.Iterator;
import java.util.List;
import java.util.Arrays;

List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("d", "e", "f");

// Chain multiple iterators
Iterator<String> chained = IteratorUtils.chainedIterator(list1.iterator(), list2.iterator());
// Iterates through: a, b, c, d, e, f

// Filter iterator
Iterator<String> filtered = IteratorUtils.filteredIterator(list1.iterator(), s -> s.compareTo("b") >= 0);
// Iterates through: b, c

// Transform iterator  
Iterator<String> transformed = IteratorUtils.transformedIterator(list1.iterator(), String::toUpperCase);
// Iterates through: A, B, C

// Get single element safely
String first = IteratorUtils.get(list1.iterator(), 0);        // "a"
String outOfBounds = IteratorUtils.get(list1.iterator(), 10); // null

// Convert to list
List<String> listFromIterator = IteratorUtils.toList(list1.iterator());

// Count elements
int count = IteratorUtils.size(list1.iterator()); // 3

// Check if iterator contains element
boolean contains = IteratorUtils.contains(list1.iterator(), "b"); // true

Key IteratorUtils Methods

/**
 * Chains multiple iterators into a single iterator
 */
static <E> Iterator<E> chainedIterator(Iterator<? extends E>... iterators);

/**
 * Creates an iterator that filters elements based on a predicate
 */
static <E> Iterator<E> filteredIterator(Iterator<? extends E> iterator, Predicate<? super E> predicate);

/**
 * Creates an iterator that transforms elements using a transformer
 */
static <I, O> Iterator<O> transformedIterator(Iterator<? extends I> iterator, Transformer<? super I, ? extends O> transformer);

/**
 * Gets the element at the specified index, returns null if out of bounds
 */
static <E> E get(Iterator<E> iterator, int index);

/**
 * Converts iterator to a list
 */
static <E> List<E> toList(Iterator<? extends E> iterator);

/**
 * Returns the number of elements in the iterator
 */
static int size(Iterator<?> iterator);

/**
 * Checks if iterator contains the specified element
 */
static boolean contains(Iterator<?> iterator, Object object);

/**
 * Creates an empty iterator
 */
static <E> Iterator<E> emptyIterator();

/**
 * Creates a single-element iterator
 */
static <E> Iterator<E> singletonIterator(E object);

IterableUtils - Iterable Operations

Utilities for working with Iterable objects, providing similar functionality to IteratorUtils but for iterables.

import org.apache.commons.collections4.IterableUtils;
import java.util.List;
import java.util.Arrays;

List<String> list1 = Arrays.asList("apple", "banana", "cherry");
List<String> list2 = Arrays.asList("date", "elderberry");

// Chain multiple iterables
Iterable<String> chained = IterableUtils.chainedIterable(list1, list2);
// Contains: apple, banana, cherry, date, elderberry

// Filter iterable
Iterable<String> longFruits = IterableUtils.filteredIterable(list1, s -> s.length() > 5);
// Contains: banana, cherry

// Transform iterable
Iterable<String> upperCase = IterableUtils.transformedIterable(list1, String::toUpperCase);
// Contains: APPLE, BANANA, CHERRY

// Get element at index safely
String first = IterableUtils.get(list1, 0);        // "apple"
String outOfBounds = IterableUtils.get(list1, 10); // null

// Check operations
boolean isEmpty = IterableUtils.isEmpty(list1);     // false
boolean contains = IterableUtils.contains(list1, "banana"); // true

// Size and counting
int size = IterableUtils.size(list1);              // 3
int matchCount = IterableUtils.frequency(list1, "apple"); // 1

// Convert to string
String joined = IterableUtils.toString(list1);     // [apple, banana, cherry]
String custom = IterableUtils.toString(list1, item -> item.toUpperCase()); // [APPLE, BANANA, CHERRY]

Key IterableUtils Methods

/**
 * Creates a chained iterable from multiple iterables
 */
static <E> Iterable<E> chainedIterable(Iterable<? extends E>... iterables);

/**
 * Creates a filtered iterable based on a predicate
 */
static <E> Iterable<E> filteredIterable(Iterable<E> iterable, Predicate<? super E> predicate);

/**
 * Creates a transformed iterable using a transformer
 */
static <I, O> Iterable<O> transformedIterable(Iterable<I> iterable, Transformer<? super I, ? extends O> transformer);

/**
 * Gets element at specified index, returns null if out of bounds
 */
static <E> E get(Iterable<E> iterable, int index);

/**
 * Checks if iterable is empty
 */
static boolean isEmpty(Iterable<?> iterable);

/**
 * Returns the number of elements in the iterable
 */
static int size(Iterable<?> iterable);

/**
 * Counts frequency of specified element
 */
static int frequency(Iterable<?> iterable, Object obj);

/**
 * Converts iterable to string representation
 */
static String toString(Iterable<?> iterable);

EnumerationUtils - Enumeration Operations

Utilities for working with the legacy Enumeration interface, providing conversions and operations.

import org.apache.commons.collections4.EnumerationUtils;
import java.util.Enumeration;
import java.util.Vector;
import java.util.List;
import java.util.Iterator;

// Legacy code often uses Vector with Enumeration
Vector<String> vector = new Vector<>();
vector.add("item1");
vector.add("item2");
vector.add("item3");

Enumeration<String> enumeration = vector.elements();

// Convert enumeration to list
List<String> list = EnumerationUtils.toList(enumeration);
// Result: [item1, item2, item3]

// Convert enumeration to iterator (for modern iteration patterns)
Iterator<String> iterator = EnumerationUtils.asIterator(enumeration);

// Convert iterator to enumeration (when interfacing with legacy APIs)
Iterator<String> modernIterator = list.iterator();
Enumeration<String> legacyEnum = EnumerationUtils.asEnumeration(modernIterator);

// Get enumeration from iterable
Enumeration<String> fromIterable = EnumerationUtils.asEnumeration(list);

Key EnumerationUtils Methods

/**
 * Converts an enumeration to a list
 */
static <E> List<E> toList(Enumeration<? extends E> enumeration);

/**
 * Converts an enumeration to an iterator
 */
static <E> Iterator<E> asIterator(Enumeration<? extends E> enumeration);

/**
 * Converts an iterator to an enumeration
 */
static <E> Enumeration<E> asEnumeration(Iterator<? extends E> iterator);

/**
 * Converts an iterable to an enumeration
 */
static <E> Enumeration<E> asEnumeration(Iterable<? extends E> iterable);

Collection utilities in Apache Commons Collections provide powerful, null-safe operations for all common collection tasks. Use these utilities to write more robust, concise, and maintainable code while avoiding common pitfalls like null pointer exceptions and inefficient operations.

Install with Tessl CLI

npx tessl i tessl/maven-org-apache-commons--commons-collections4

docs

advanced-collections.md

bags.md

bidimaps.md

collection-utilities.md

functional-programming.md

index.md

multimaps.md

tile.json