Class CollectionUtils
This class cannot be instantiated.
- Author:
- Chakib Daii
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprivatePrivate constructor to prevent instantiation. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> booleanRecursively verifies that all elements in the given array match the provided predicate.static <T> booleanallMatch(Collection<?> collection, Predicate<T> predicate) Recursively verifies that all elements in the given collection match the provided predicate.static <T> booleanRecursively verifies that all values in the given map match the provided predicate.static Object[]applyOperation(Object[] arr, Number scalar, boolean isLeftOperand, BinaryOperation operation) Applies a binary operation between each element of an array and a scalar number.static Object[]applyOperation(Object[] left, Object[] right, BinaryOperation operation) Applies a binary operation element-wise to two arrays of objects.static Object[]applyOperation(Object[] arr, UnaryOperation operation) Applies a unary operation to each element in an array.static Collection<?>applyOperation(Collection<?> collection, Number scalar, boolean isLeftOperand, BinaryOperation operation) Applies a binary operation between each element of a collection and a scalar number.static Collection<?>applyOperation(Collection<?> left, Collection<?> right, BinaryOperation operation) Applies a binary operation element-wise to two collections.static Collection<?>applyOperation(Collection<?> collection, UnaryOperation operation) Applies a unary operation to each element in a collection.static Map<?,?> applyOperation(Map<?, ?> map, Number scalar, boolean isLeftOperand, BinaryOperation operation) Applies a binary operation between each value in a map and a scalar number.static Map<?,?> applyOperation(Map<?, ?> left, Map<?, ?> right, BinaryOperation operation) Applies a binary operation element-wise to two maps.static Map<?,?> applyOperation(Map<?, ?> map, UnaryOperation operation) Applies a unary operation to each value in a map.static StringarrayToString(Object obj, char prefix, char suffix) Converts an array to a string representation, handling both primitive and object arrays.static Collection<Object>createCollection(Class<?> collectionType) Creates a newCollectioninstance of the specified type.static <T> Collection<T>createCompatibleCollection(Collection<T> original) Creates a new, empty collection that is compatible with the given original collection, in order to preserve its iteration order and general behavior.static <K,V> Map<K, V> Creates a newMapinstance of the specified type.static ObjectgetElementAt(Collection<?> collection, int targetIndex) Retrieves the element at the specified index from aCollection.static booleanDetermines whether the specified object represents a collection-like structure: aCollection,Map, or an array.static booleanDetermines whether the specified object represents a tuple-like or collection-like structure.static NaftahBugErrornewNaftahIndexOutOfBoundsBugError(int targetIndex, int size) Creates aNaftahBugErrorindicating that an index is out of bounds for a collection.static NaftahBugErrornewNaftahIndexOutOfBoundsBugError(int targetIndex, int size, Exception e, int line, int column) Creates aNaftahBugErrorindicating that an index is out of bounds for a collection, and optionally includes a cause (wrapped exception).static NaftahBugErrornewNaftahSizeBugError(Object[] left, Object[] right) Constructs a newNaftahBugErrorindicating that the sizes of the two arrays do not match.static NaftahBugErrornewNaftahSizeBugError(Map<?, ?> left, Map<?, ?> right) Constructs a newNaftahBugErrorindicating that the sizes of the two associative arrays (maps) do not match.static Objectreduce(Object[] array, BinaryOperator<Object> combiner) Reduces the elements of the given array into a single value using the specified combining operator.static Objectreduce(Collection<Object> collection, BinaryOperator<Object> combiner) Reduces the elements of the given collection into a single value using the specified combining operator.static Objectreduce(Map<?, Object> map, BinaryOperator<Object> combiner) Reduces the values of the given map into a single value using the specified combining operator.static ObjectremoveElementAt(Collection<?> collection, int targetIndex) Removes and returns the element at the specified index from the given collection.static <T> voidsetElementAt(Collection<T> collection, int targetIndex, T newValue) Replaces the element at the specified index in aCollectionwith a new value.static Object[]toObjectArray(Object array) Converts any Java array (including primitive arrays) into an Object[].static StringConverts an arbitrary object into its Arabic string representation.static StringConverts an arbitrary object into its Arabic string representation.static <K,V> String Converts aMapinto a string representation using the specified prefix and suffix characters.static <T> StringtoString(T[] a, char prefix, char suffix) Converts an array into a string representation using the specified prefix and suffix characters.
-
Constructor Details
-
CollectionUtils
private CollectionUtils()Private constructor to prevent instantiation. Always throws aNaftahBugErrorwhen called.
-
-
Method Details
-
applyOperation
Applies a binary operation element-wise to two arrays of objects.- Parameters:
left- the first arrayright- the second arrayoperation- the binary operation to apply- Returns:
- a new array containing the results of the operation
- Throws:
NaftahBugError- if arrays have different lengths
-
applyOperation
public static Collection<?> applyOperation(Collection<?> left, Collection<?> right, BinaryOperation operation) Applies a binary operation element-wise to two collections.- Parameters:
left- the first collectionright- the second collectionoperation- the binary operation to apply- Returns:
- a new collection containing the results of the operation
- Throws:
NaftahBugError- if collections have different sizes
-
applyOperation
public static Object[] applyOperation(Object[] arr, Number scalar, boolean isLeftOperand, BinaryOperation operation) Applies a binary operation between each element of an array and a scalar number.- Parameters:
arr- the array of objectsscalar- the scalar numberisLeftOperand- is the array left operandoperation- the binary operation to apply- Returns:
- a new array containing the results of the operation
-
applyOperation
public static Collection<?> applyOperation(Collection<?> collection, Number scalar, boolean isLeftOperand, BinaryOperation operation) Applies a binary operation between each element of a collection and a scalar number.- Parameters:
collection- the collection of objectsscalar- the scalar numberisLeftOperand- is the collection left operandoperation- the binary operation to apply- Returns:
- a new collection containing the results of the operation
-
applyOperation
Applies a binary operation element-wise to two maps. The keys of the first map must exist in the second map.- Parameters:
left- the first mapright- the second mapoperation- the binary operation to apply- Returns:
- a new map containing the results of the operation
- Throws:
NaftahBugError- if a key from the first map is missing in the second map
-
applyOperation
public static Map<?,?> applyOperation(Map<?, ?> map, Number scalar, boolean isLeftOperand, BinaryOperation operation) Applies a binary operation between each value in a map and a scalar number.- Parameters:
map- the map of key-value pairsscalar- the scalar numberisLeftOperand- is the map left operandoperation- the binary operation to apply- Returns:
- a new map containing the results of the operation
-
applyOperation
Applies a unary operation to each element in an array.- Parameters:
arr- the array of objectsoperation- the unary operation to apply- Returns:
- a new array containing the results of the operation
-
applyOperation
Applies a unary operation to each element in a collection.- Parameters:
collection- the collection of objectsoperation- the unary operation to apply- Returns:
- a new collection containing the results of the operation
-
applyOperation
Applies a unary operation to each value in a map.- Parameters:
map- the map of key-value pairsoperation- the unary operation to apply- Returns:
- a new map containing the results of the operation
-
getElementAt
Retrieves the element at the specified index from aCollection.Since
Collectiondoes not support direct index-based access, this method iterates through the elements in the order defined by the collection's iterator.If the index is out of bounds (i.e.,
targetIndex >= collection.size()), aNaftahBugErroris thrown with a detailed Arabic error message.- Parameters:
collection- the collection to retrieve the element fromtargetIndex- the zero-based index of the desired element- Returns:
- the element at the specified index
- Throws:
NaftahBugError- if the index is greater than or equal to the collection size
-
removeElementAt
Removes and returns the element at the specified index from the given collection.This method provides an index-based removal operation for any
Collectiontype that supports element removal via anIterator. It iterates over the collection until the target index is reached, removes that element, and returns it.If the collection's size is less than or equal to
targetIndex, anIndexOutOfBoundsException-like error is thrown usingnewNaftahIndexOutOfBoundsBugError(int, int).Behavior details:
- Removes the element at the specified zero-based index.
- Returns the removed element.
- Returns
None.get()if the element cannot be found (which should not occur if the bounds check passes).
This method does not support random access and runs in O(n) time.
- Parameters:
collection- the collection from which to remove the element; must not benulltargetIndex- the zero-based index of the element to remove- Returns:
- the removed element, or
None.get()if no element was removed - Throws:
NaftahBugError- iftargetIndexis out of bounds for the given collection- See Also:
-
setElementAt
Replaces the element at the specified index in aCollectionwith a new value.This method iterates through the collection using an
Iterator, and rebuilds the collection with the replacement applied. It preserves insertion order for collections likeLinkedHashSetandList.- Type Parameters:
T- the element type of the collection- Parameters:
collection- the collection to modifytargetIndex- the zero-based index to replacenewValue- the new value to insert at the given index- Throws:
IndexOutOfBoundsException- if the target index is out of boundsUnsupportedOperationException- if the collection cannot be cleared or modified
-
createCompatibleCollection
Creates a new, empty collection that is compatible with the given original collection, in order to preserve its iteration order and general behavior.This is used internally to rebuild collections (e.g., when modifying an element by index), while maintaining the same ordering semantics:
- If the original is a
LinkedHashSet, returns a newLinkedHashSet. - If the original is a
List, returns a newArrayList. - If the original is a
Set, returns a newHashSet. - Otherwise, defaults to a new
ArrayListas a general-purpose fallback.
- Type Parameters:
T- the element type of the collection- Parameters:
original- the original collection to match- Returns:
- a new empty collection with behavior compatible to the original
- If the original is a
-
createCollection
Creates a newCollectioninstance of the specified type.If
collectionTypeis an interface (e.g., List, Set, Queue), a default implementation will be created (ArrayList, HashSet, LinkedList). IfcollectionTypeis a concrete class, an attempt is made to create a new instance using the default constructor.- Parameters:
collectionType- the collection type to instantiate.- Returns:
- a new collection instance of the requested type.
-
createMap
Creates a newMapinstance of the specified type.If the provided
mapTyperepresents a concrete class, this method attempts to instantiate it using its no-argument constructor. If instantiation fails or if the type is an interface, a default implementation is chosen based on the type hierarchy:SortedMap→TreeMapLinkedHashMap→LinkedHashMap- Any other type →
HashMap
- Type Parameters:
K- the type of keys maintained by the mapV- the type of mapped values- Parameters:
mapType- theClassrepresenting the map type to instantiate- Returns:
- a new
Mapinstance of the requested type, or a default implementation if instantiation fails - Throws:
NullPointerException- ifmapTypeisnull
-
toObjectArray
Converts any Java array (including primitive arrays) into an Object[]. This is reflection-safe and never throws ClassCastException.- Parameters:
array- the source array (e.g. int[], String[], Object[], etc.)- Returns:
- an Object[] containing all elements, or an empty array if null
- Throws:
IllegalArgumentException- if the input is not an array
-
allMatch
Recursively verifies that all elements in the given collection match the provided predicate.Nested structures (collections, maps, arrays) are traversed and evaluated recursively.
- Type Parameters:
T- the expected element type- Parameters:
collection- the collection to evaluatepredicate- the predicate to test each element against- Returns:
trueif all elements (and nested elements) match the predicate;falseotherwise
-
allMatch
Recursively verifies that all elements in the given array match the provided predicate.Nested structures (collections, maps, arrays) are traversed and evaluated recursively.
- Type Parameters:
T- the expected element type- Parameters:
array- the array to evaluatepredicate- the predicate to test each element against- Returns:
trueif all elements (and nested elements) match the predicate;falseotherwise
-
allMatch
Recursively verifies that all values in the given map match the provided predicate.Nested structures (collections, maps, arrays) are traversed and evaluated recursively.
- Type Parameters:
T- the expected element type- Parameters:
map- the map whose values to evaluatepredicate- the predicate to test each value against- Returns:
trueif all values (and nested values) match the predicate;falseotherwise
-
reduce
Reduces the elements of the given collection into a single value using the specified combining operator.The reduction is performed in iteration order, starting with the first element as the initial value.
- Parameters:
collection- the collection to reducecombiner- the operator used to combine two elements into one- Returns:
- the result of the reduction, or
nullif the collection is empty
-
reduce
Reduces the elements of the given array into a single value using the specified combining operator.The reduction is performed in iteration order, starting with the first element as the initial value.
- Parameters:
array- the array to reducecombiner- the operator used to combine two elements into one- Returns:
- the result of the reduction, or
nullif the array is empty
-
reduce
Reduces the values of the given map into a single value using the specified combining operator.The reduction is performed over the map's values in iteration order.
- Parameters:
map- the map whose values to reducecombiner- the operator used to combine two elements into one- Returns:
- the result of the reduction, or
nullif the map is empty
-
isCollectionMapOrArray
Determines whether the specified object represents a collection-like structure: aCollection,Map, or an array.This method is intended for dynamic type inspection in recursive utilities that traverse or process heterogeneous object graphs.
- Parameters:
obj- the object to inspect (may benull)- Returns:
trueif the object is aCollection,Map, or an array;falseotherwise
-
isCollectionMapOrArrayOrTuple
Determines whether the specified object represents a tuple-like or collection-like structure.This method extends
isCollectionMapOrArray(Object)by also recognizingNTupleinstances.- Parameters:
obj- the object to inspect (may benull)- Returns:
trueif the object is anNTuple,Collection,Map, or an array;falseotherwise
-
newNaftahSizeBugError
Constructs a newNaftahBugErrorindicating that the sizes of the two arrays do not match.- Parameters:
left- the first arrayright- the second array- Returns:
- a new NaftahBugError with a descriptive message in Arabic
-
newNaftahSizeBugError
Constructs a newNaftahBugErrorindicating that the sizes of the two associative arrays (maps) do not match.- Parameters:
left- the first associative array (map)right- the second associative array (map)- Returns:
- a new NaftahBugError with a descriptive message in Arabic showing both maps
-
newNaftahIndexOutOfBoundsBugError
Creates aNaftahBugErrorindicating that an index is out of bounds for a collection.This version does not include a cause (exception).
- Parameters:
targetIndex- the index that was attempted to be accessedsize- the size of the collection at the time of access- Returns:
- a
NaftahBugErrorwith a detailed Arabic error message
-
newNaftahIndexOutOfBoundsBugError
public static NaftahBugError newNaftahIndexOutOfBoundsBugError(int targetIndex, int size, Exception e, int line, int column) Creates aNaftahBugErrorindicating that an index is out of bounds for a collection, and optionally includes a cause (wrapped exception).- Parameters:
targetIndex- the index that was attempted to be accessedsize- the size of the collection at the time of accesse- an optional cause of the error (can benull)line- The line number on which the 1st character of this token was matchedcolumn- The index of the first character of this token relative to the beginning of the line at which it occurs- Returns:
- a
NaftahBugErrorwith a detailed Arabic error message and optional cause
-
toString
Converts an arbitrary object into its Arabic string representation.This method detects the object's runtime type and renders it accordingly:
List→ قائمةSet→ مجموعةTuple→ تركيبةMap→ كائن / مصفوفة ترابطية- Array → قائمة
- Other → uses
getNaftahValueToString(o)
- Parameters:
o- the object to convert- Returns:
- a string in Arabic describing the object's structure and contents
-
toString
Converts an arbitrary object into its Arabic string representation.This method detects the object's runtime type and renders it accordingly:
List→ قائمةSet→ مجموعةTuple→ تركيبةMap→ كائن / مصفوفة ترابطية- Array → قائمة
- Other → uses
getNaftahValueToString(o)
- Parameters:
o- the object to convertnaftahObject- marks that the object to convert is naftah object- Returns:
- a string in Arabic describing the object's structure and contents
-
arrayToString
Converts an array to a string representation, handling both primitive and object arrays.This method works for any array type, including nested arrays of primitives or objects. Each element is converted to a string using
ObjectUtils.getNaftahValueToString(Object). The resulting string is enclosed between the specifiedprefixandsuffixcharacters, and elements are separated by commas.Examples:
int[] ints = {1, 2, 3}; arrayToString(ints, '[', ']'); // returns "[1, 2, 3]" String[] strs = {"a", "b"}; arrayToString(strs, '(', ')'); // returns "(a, b)"- Parameters:
obj- the array object to convert; may be a primitive array, object array, ornullprefix- the character to put at the beginning of the string representationsuffix- the character to put at the end of the string representation- Returns:
- a string representation of the array, or
NULLif the array isnull - See Also:
-
toString
Converts an array into a string representation using the specified prefix and suffix characters.Each element is converted via
ObjectUtils.getNaftahValueToString(Object).- Type Parameters:
T- the type of elements in the array- Parameters:
a- the array to convert (can benull)prefix- the opening character (e.g., '[', '(', '{')suffix- the closing character (e.g., ']', ')', '}')- Returns:
- a formatted Arabic string representing the array contents
-
toString
Converts aMapinto a string representation using the specified prefix and suffix characters.Keys and values are converted to strings, with recursive detection for self-references (to prevent infinite loops).
- Type Parameters:
K- the key typeV- the value type- Parameters:
map- the map to convert (can benull)prefix- the opening character (e.g., '{')suffix- the closing character (e.g., '}')- Returns:
- a formatted Arabic string representing the map entries
-