Class CollectionUtils

java.lang.Object
org.daiitech.naftah.builtin.utils.CollectionUtils

public final class CollectionUtils extends Object
Utility class for applying binary and unary operations on collections, arrays, and maps.

This class cannot be instantiated.

Author:
Chakib Daii
  • Constructor Details

    • CollectionUtils

      private CollectionUtils()
      Private constructor to prevent instantiation. Always throws a NaftahBugError when called.
  • Method Details

    • applyOperation

      public static Object[] applyOperation(Object[] left, Object[] right, BinaryOperation operation)
      Applies a binary operation element-wise to two arrays of objects.
      Parameters:
      left - the first array
      right - the second array
      operation - 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 collection
      right - the second collection
      operation - 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 objects
      scalar - the scalar number
      isLeftOperand - is the array left operand
      operation - 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 objects
      scalar - the scalar number
      isLeftOperand - is the collection left operand
      operation - the binary operation to apply
      Returns:
      a new collection containing the results of the operation
    • applyOperation

      public static Map<?,?> applyOperation(Map<?,?> left, Map<?,?> right, BinaryOperation operation)
      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 map
      right - the second map
      operation - 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 pairs
      scalar - the scalar number
      isLeftOperand - is the map left operand
      operation - the binary operation to apply
      Returns:
      a new map containing the results of the operation
    • applyOperation

      public static Object[] applyOperation(Object[] arr, UnaryOperation operation)
      Applies a unary operation to each element in an array.
      Parameters:
      arr - the array of objects
      operation - the unary operation to apply
      Returns:
      a new array containing the results of the operation
    • applyOperation

      public static Collection<?> applyOperation(Collection<?> collection, UnaryOperation operation)
      Applies a unary operation to each element in a collection.
      Parameters:
      collection - the collection of objects
      operation - the unary operation to apply
      Returns:
      a new collection containing the results of the operation
    • applyOperation

      public static Map<?,?> applyOperation(Map<?,?> map, UnaryOperation operation)
      Applies a unary operation to each value in a map.
      Parameters:
      map - the map of key-value pairs
      operation - the unary operation to apply
      Returns:
      a new map containing the results of the operation
    • getElementAt

      public static Object getElementAt(Collection<?> collection, int targetIndex)
      Retrieves the element at the specified index from a Collection.

      Since Collection does 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()), a NaftahBugError is thrown with a detailed Arabic error message.

      Parameters:
      collection - the collection to retrieve the element from
      targetIndex - 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

      public static Object removeElementAt(Collection<?> collection, int targetIndex)
      Removes and returns the element at the specified index from the given collection.

      This method provides an index-based removal operation for any Collection type that supports element removal via an Iterator. 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, an IndexOutOfBoundsException-like error is thrown using newNaftahIndexOutOfBoundsBugError(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 be null
      targetIndex - the zero-based index of the element to remove
      Returns:
      the removed element, or None.get() if no element was removed
      Throws:
      NaftahBugError - if targetIndex is out of bounds for the given collection
      See Also:
    • setElementAt

      public static <T> void setElementAt(Collection<T> collection, int targetIndex, T newValue)
      Replaces the element at the specified index in a Collection with 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 like LinkedHashSet and List.

      Type Parameters:
      T - the element type of the collection
      Parameters:
      collection - the collection to modify
      targetIndex - the zero-based index to replace
      newValue - the new value to insert at the given index
      Throws:
      IndexOutOfBoundsException - if the target index is out of bounds
      UnsupportedOperationException - if the collection cannot be cleared or modified
    • createCompatibleCollection

      public 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.

      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 new LinkedHashSet.
      • If the original is a List, returns a new ArrayList.
      • If the original is a Set, returns a new HashSet.
      • Otherwise, defaults to a new ArrayList as 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
    • createCollection

      public static Collection<Object> createCollection(Class<?> collectionType)
      Creates a new Collection instance of the specified type.

      If collectionType is an interface (e.g., List, Set, Queue), a default implementation will be created (ArrayList, HashSet, LinkedList). If collectionType is 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

      public static <K, V> Map<K,V> createMap(Class<?> mapType)
      Creates a new Map instance of the specified type.

      If the provided mapType represents 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:

      Type Parameters:
      K - the type of keys maintained by the map
      V - the type of mapped values
      Parameters:
      mapType - the Class representing the map type to instantiate
      Returns:
      a new Map instance of the requested type, or a default implementation if instantiation fails
      Throws:
      NullPointerException - if mapType is null
    • toObjectArray

      public static Object[] toObjectArray(Object array)
      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

      public static <T> boolean allMatch(Collection<?> collection, Predicate<T> predicate)
      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 evaluate
      predicate - the predicate to test each element against
      Returns:
      true if all elements (and nested elements) match the predicate; false otherwise
    • allMatch

      public static <T> boolean allMatch(Object[] array, Predicate<T> predicate)
      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 evaluate
      predicate - the predicate to test each element against
      Returns:
      true if all elements (and nested elements) match the predicate; false otherwise
    • allMatch

      public static <T> boolean allMatch(Map<?,?> map, Predicate<T> predicate)
      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 evaluate
      predicate - the predicate to test each value against
      Returns:
      true if all values (and nested values) match the predicate; false otherwise
    • reduce

      public static Object reduce(Collection<Object> collection, BinaryOperator<Object> combiner)
      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 reduce
      combiner - the operator used to combine two elements into one
      Returns:
      the result of the reduction, or null if the collection is empty
    • reduce

      public static Object reduce(Object[] array, BinaryOperator<Object> combiner)
      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 reduce
      combiner - the operator used to combine two elements into one
      Returns:
      the result of the reduction, or null if the array is empty
    • reduce

      public static Object reduce(Map<?,Object> map, BinaryOperator<Object> combiner)
      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 reduce
      combiner - the operator used to combine two elements into one
      Returns:
      the result of the reduction, or null if the map is empty
    • isCollectionMapOrArray

      public static boolean isCollectionMapOrArray(Object obj)
      Determines whether the specified object represents a collection-like structure: a Collection, 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 be null)
      Returns:
      true if the object is a Collection, Map, or an array; false otherwise
    • isCollectionMapOrArrayOrTuple

      public static boolean isCollectionMapOrArrayOrTuple(Object obj)
      Determines whether the specified object represents a tuple-like or collection-like structure.

      This method extends isCollectionMapOrArray(Object) by also recognizing NTuple instances.

      Parameters:
      obj - the object to inspect (may be null)
      Returns:
      true if the object is an NTuple, Collection, Map, or an array; false otherwise
    • newNaftahSizeBugError

      public static NaftahBugError newNaftahSizeBugError(Object[] left, Object[] right)
      Constructs a new NaftahBugError indicating that the sizes of the two arrays do not match.
      Parameters:
      left - the first array
      right - the second array
      Returns:
      a new NaftahBugError with a descriptive message in Arabic
    • newNaftahSizeBugError

      public static NaftahBugError newNaftahSizeBugError(Map<?,?> left, Map<?,?> right)
      Constructs a new NaftahBugError indicating 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

      public static NaftahBugError newNaftahIndexOutOfBoundsBugError(int targetIndex, int size)
      Creates a NaftahBugError indicating 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 accessed
      size - the size of the collection at the time of access
      Returns:
      a NaftahBugError with a detailed Arabic error message
    • newNaftahIndexOutOfBoundsBugError

      public static NaftahBugError newNaftahIndexOutOfBoundsBugError(int targetIndex, int size, Exception e, int line, int column)
      Creates a NaftahBugError indicating 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 accessed
      size - the size of the collection at the time of access
      e - an optional cause of the error (can be null)
      line - The line number on which the 1st character of this token was matched
      column - The index of the first character of this token relative to the beginning of the line at which it occurs
      Returns:
      a NaftahBugError with a detailed Arabic error message and optional cause
    • toString

      public static String toString(Object o)
      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

      public static String toString(Object o, boolean naftahObject)
      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
      naftahObject - marks that the object to convert is naftah object
      Returns:
      a string in Arabic describing the object's structure and contents
    • arrayToString

      public static String arrayToString(Object obj, char prefix, char suffix)
      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 specified prefix and suffix characters, 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, or null
      prefix - the character to put at the beginning of the string representation
      suffix - the character to put at the end of the string representation
      Returns:
      a string representation of the array, or NULL if the array is null
      See Also:
    • toString

      public static <T> String toString(T[] a, char prefix, char suffix)
      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 be null)
      prefix - the opening character (e.g., '[', '(', '{')
      suffix - the closing character (e.g., ']', ')', '}')
      Returns:
      a formatted Arabic string representing the array contents
    • toString

      public static <K, V> String toString(Map<K,V> map, char prefix, char suffix)
      Converts a Map into 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 type
      V - the value type
      Parameters:
      map - the map to convert (can be null)
      prefix - the opening character (e.g., '{')
      suffix - the closing character (e.g., '}')
      Returns:
      a formatted Arabic string representing the map entries