Class Utils

java.lang.Object
org.apache.juneau.common.utils.Utils
Direct Known Subclasses:
Utils2

public class Utils extends Object
Common utility methods.

This class contains various static utility methods for working with collections, strings, objects, and other common operations.

  • Constructor Details

    • Utils

      protected Utils()
      Constructor - This class is meant to be subclasses.
  • Method Details

    • a

      @SafeVarargs public static <T> T[] a(T... x)
      Creates an array of objects.
      Type Parameters:
      T - The component type of the array.
      Parameters:
      x - The objects to place in the array.
      Returns:
      A new array containing the specified objects.
    • accumulate

      public static <T> List<T> accumulate(Object o)
      Traverses all elements in the specified object and accumulates them into a list.
      Type Parameters:
      T - The element type.
      Parameters:
      o - The object to traverse.
      Returns:
      A list containing all accumulated elements.
    • alist

      @SafeVarargs public static <T> List<T> alist(T... values)
      Shortcut for creating an unmodifiable list out of an array of values.
      Type Parameters:
      T - The element type.
      Parameters:
      values - The values to add to the list.
      Returns:
      An unmodifiable list containing the specified values, or null if the input is null.
    • array

      public static <E> E[] array(Collection<E> value, Class<E> componentType)
      Converts the specified collection to an array.
      Type Parameters:
      E - The element type.
      Parameters:
      value - The collection to convert.
      componentType - The component type of the array.
      Returns:
      A new array.
    • arrayToList

      public static List<Object> arrayToList(Object array)
      Converts any array (including primitive arrays) to a List.
      Parameters:
      array - The array to convert. Can be any array type including primitives.
      Returns:
      A List containing the array elements. Primitive values are auto-boxed. Returns null if the input is null.
      Throws:
      IllegalArgumentException - if the input is not an array.
    • assertArg

      public static final void assertArg(boolean expression, String msg, Object... args) throws IllegalArgumentException
      Throws an IllegalArgumentException if the specified expression is false.
      Example:

      import static org.apache.juneau.internal.ArgUtils.*; public String setFoo(List<String> foo) { assertArg(foo != null && ! foo.isEmpty(), "'foo' cannot be null or empty."); ... }

      Parameters:
      expression - The boolean expression to check.
      msg - The exception message.
      args - The exception message args.
      Throws:
      IllegalArgumentException - Constructed exception.
    • assertArgNotNull

      public static final <T> T assertArgNotNull(String name, T o) throws IllegalArgumentException
      Throws an IllegalArgumentException if the specified argument is null.
      Example:

      import static org.apache.juneau.internal.ArgUtils.*; public String setFoo(String foo) { assertArgNotNull("foo", foo); ... }

      Type Parameters:
      T - The argument data type.
      Parameters:
      name - The argument name.
      o - The object to check.
      Returns:
      The same argument.
      Throws:
      IllegalArgumentException - Constructed exception.
    • assertArgNotNullOrBlank

      public static final String assertArgNotNullOrBlank(String name, String o) throws IllegalArgumentException
      Throws an IllegalArgumentException if the specified string is null or blank.
      Parameters:
      name - The argument name.
      o - The object to check.
      Returns:
      The same object.
      Throws:
      IllegalArgumentException - Thrown if the specified string is null or blank.
    • assertVarargsNotNull

      public static final <T> T[] assertVarargsNotNull(String name, T[] o) throws IllegalArgumentException
      Throws an IllegalArgumentException if the specified varargs array or any of its elements are null.
      Type Parameters:
      T - The element type.
      Parameters:
      name - The argument name.
      o - The object to check.
      Returns:
      The same object.
      Throws:
      IllegalArgumentException - Thrown if the specified varargs array or any of its elements are null.
    • assertClassArrayArgIsType

      public static final <E> Class<E>[] assertClassArrayArgIsType(String name, Class<E> type, Class<?>[] value) throws IllegalArgumentException
      Throws an IllegalArgumentException if the specified value doesn't have all subclasses of the specified type.
      Type Parameters:
      E - The element type.
      Parameters:
      name - The argument name.
      type - The expected parent class.
      value - The array value being checked.
      Returns:
      The value cast to the specified array type.
      Throws:
      IllegalArgumentException - Constructed exception.
    • cast

      public static <T> T cast(Class<T> c, Object o)
      Casts an object to a specific type if it's an instance of that type.
      Type Parameters:
      T - The type to cast to.
      Parameters:
      c - The type to cast to.
      o - The object to cast to.
      Returns:
      The cast object, or null if the object wasn't the specified type.
    • castOrNull

      public static <T> T castOrNull(Object o, Class<T> c)
      If the specified object is an instance of the specified class, casts it to that type.
      Type Parameters:
      T - The class to cast to.
      Parameters:
      o - The object to cast.
      c - The class to cast to.
      Returns:
      The cast object, or null if the object wasn't an instance of the specified class.
    • compare

      public static int compare(Object o1, Object o2)
      Compares two objects for equality.

      Nulls are always considered less-than unless both are null.

      Parameters:
      o1 - Object 1.
      o2 - Object 2.
      Returns:
      -1, 0, or 1 if o1 is less-than, equal, or greater-than o2.
      0 if objects are not of the same type or do not implement the Comparable interface.
    • contains

      public static boolean contains(String s, char... values)
      Null-safe String.contains(CharSequence) operation.
      Parameters:
      s - The string to check.
      values - The characters to check for.
      Returns:
      true if the string contains any of the specified characters.
    • contains

      public static boolean contains(String s, String... values)
      Null-safe String.contains(CharSequence) operation.
      Parameters:
      s - The string to check.
      values - The substrings to check for.
      Returns:
      true if the string contains any of the specified substrings.
    • ea

      public static <T> T[] ea(Class<T> type)
      Creates an empty array of the specified type.
      Type Parameters:
      T - The component type of the array.
      Parameters:
      type - The component type class.
      Returns:
      An empty array of the specified type.
    • elist

      public static <T> List<T> elist(Class<T> type)
      Shortcut for creating an empty list of the specified type.
      Type Parameters:
      T - The element type.
      Parameters:
      type - The element type class.
      Returns:
      An empty list.
    • emap

      public static <K, V> Map<K,V> emap(Class<K> keyType, Class<V> valueType)
      Shortcut for creating an empty map of the specified types.
      Type Parameters:
      K - The key type.
      V - The value type.
      Parameters:
      keyType - The key type class.
      valueType - The value type class.
      Returns:
      An empty unmodifiable map.
    • empty

      public static <T> Optional<T> empty()
      Returns an empty Optional.
      Type Parameters:
      T - The component type.
      Returns:
      An empty Optional.
    • emptyIfNull

      public static String emptyIfNull(Object value)
      Returns the specified string, or blank if that string is null.
      Parameters:
      value - The value to convert to a string.
      Returns:
      The string representation of the value, or an empty string if null.
    • env

      public static Optional<String> env(String name)
      Looks up a system property or environment variable.

      First looks in system properties. Then converts the name to env-safe and looks in the system environment. Then returns the default if it can't be found.

      Parameters:
      name - The property name.
      Returns:
      The value if found.
    • env

      public static <T> T env(String name, T def)
      Looks up a system property or environment variable.

      First looks in system properties. Then converts the name to env-safe and looks in the system environment. Then returns the default if it can't be found.

      Type Parameters:
      T - The type to convert the value to.
      Parameters:
      name - The property name.
      def - The default value if not found.
      Returns:
      The default value.
    • eq

      public static boolean eq(boolean caseInsensitive, String s1, String s2)
      Tests two strings for equality, but gracefully handles nulls.
      Parameters:
      caseInsensitive - Use case-insensitive matching.
      s1 - String 1.
      s2 - String 2.
      Returns:
      true if the strings are equal.
    • eq

      public static <T> boolean eq(T o1, T o2)
      Tests two objects for equality, gracefully handling nulls and arrays.
      Type Parameters:
      T - The value types.
      Parameters:
      o1 - Object 1.
      o2 - Object 2.
      Returns:
      true if both objects are equal based on the Object.equals(Object) method.
    • eq

      public static <T, U> boolean eq(T o1, U o2, BiPredicate<T,U> test)
      Tests two objects for equality, gracefully handling nulls. Allows you to simplify object comparison without sacrificing efficiency. Example: public boolean equals(Object o) return eq(this, (Role)o, (x,y)->eq(x.id,y.id) && eq(x.name,y.name) && eq(x.created,y.created) && eq(x.createdBy,y.createdBy)); }
      Type Parameters:
      T - Object 1 type.
      U - Object 2 type.
      Parameters:
      o1 - Object 1.
      o2 - Object 2.
      test - The test to use for equality.
      Returns:
      true if both objects are equal based on the test.
    • eqic

      public static boolean eqic(String s1, String s2)
      Tests two strings for case-insensitive equality, but gracefully handles nulls.
      Parameters:
      s1 - String 1.
      s2 - String 2.
      Returns:
      true if the strings are equal.
    • f

      public static String f(String pattern, Object... args)
      Same as MessageFormat.format().
      Parameters:
      pattern - The message pattern.
      args - The arguments to substitute into the pattern.
      Returns:
      The formatted string.
    • firstNonNull

      @SafeVarargs public static <T> T firstNonNull(T... t)
      Returns the first non-null value in the specified array
      Type Parameters:
      T - The value types.
      Parameters:
      t - The values to check.
      Returns:
      The first non-null value, or null if the array is null or empty or contains only null values.
    • fms

      public static Supplier<String> fms(String pattern, Object... args)
      Creates a formatted string supplier with message arguments for lazy evaluation.

      This method returns a Supplier that formats the string pattern with the provided arguments only when the supplier's get() method is called. This is useful for expensive string formatting operations that may not always be needed, such as error messages in assertions.

      Usage Examples:

      // Lazy evaluation - string is only formatted if assertion fails assertTrue(condition, fms("Expected {0} but got {1}", expected, actual)); // Can be used anywhere a Supplier<String> is expected Supplier<String> messageSupplier = fms("Processing item {0} of {1}", i, total);

      Parameters:
      pattern - The message pattern using {0}, {1}, etc. placeholders.
      args - The arguments to substitute into the pattern placeholders.
      Returns:
      A Supplier that will format the string when get() is called.
      See Also:
    • getMatchPattern3

      public static Pattern getMatchPattern3(String s)
      Converts a string containing "*" meta characters with a regular expression pattern.
      Parameters:
      s - The string to create a pattern from.
      Returns:
      A regular expression pattern.
    • getMatchPattern3

      public static Pattern getMatchPattern3(String s, int flags)
      Converts a string containing "*" meta characters with a regular expression pattern.
      Parameters:
      s - The string to create a pattern from.
      flags - Regular expression flags.
      Returns:
      A regular expression pattern.
    • hash

      public static final int hash(Object... values)
      Shortcut for calling Objects.hash(Object...).
      Parameters:
      values - The values to hash.
      Returns:
      A hash code value for the given values.
    • illegalArg

      public static IllegalArgumentException illegalArg(String msg, Object... args)
      Parameters:
      msg - The exception message.
      args - The arguments to substitute into the message.
      Returns:
      A new IllegalArgumentException with the formatted message.
    • isArray

      public static boolean isArray(Object o)
      Checks if the specified object is an array.
      Parameters:
      o - The object to check.
      Returns:
      true if the object is not null and is an array.
    • isEmpty

      public static boolean isEmpty(Object o)
      Returns true if the specified object is empty.

      Return true if the value is any of the following:

      • null
      • An empty Collection
      • An empty Map
      • An empty array
      • An empty CharSequence
      • An empty String when serialized to a string using Object.toString().
      Parameters:
      o - The object to test.
      Returns:
      true if the specified object is empty.
    • isEmpty

      public static boolean isEmpty(String o)
      Returns true if string is null or empty.
      Parameters:
      o - The string to check.
      Returns:
      true if string is null or empty.
    • isEmptyOrBlank

      public static boolean isEmptyOrBlank(String s)
      Returns true if specified string is null or empty or consists of only blanks.
      Parameters:
      s - The string to check.
      Returns:
      true if specified string is null or empty or consists of only blanks.
    • isNotEmpty

      public static boolean isNotEmpty(Object value)
      Returns true if the specified object is not null and not empty. Works on any of the following data types: String, CharSequence, Collection, Map, array. All other types are stringified and then checked as a String.
      Parameters:
      value - The value being checked.
      Returns:
      true if the specified object is not null and not empty.
    • isNotEmpty

      public static boolean isNotEmpty(String o)
      Returns true if string is not null and not empty.
      Parameters:
      o - The string to check.
      Returns:
      true if string is not null and not empty.
    • isNotMinusOne

      public static <T extends Number> boolean isNotMinusOne(T value)
      Returns true if the specified number is not null and not -1.
      Type Parameters:
      T - The value types.
      Parameters:
      value - The value being checked.
      Returns:
      true if the specified number is not null and not -1.
    • isNotNull

      public static <T> boolean isNotNull(T value)
      Returns true if the specified object is not null.
      Type Parameters:
      T - The value type.
      Parameters:
      value - The value being checked.
      Returns:
      true if the specified object is not null.
    • isTrue

      public static boolean isTrue(Boolean value)
      Returns true if the specified boolean is not null and is true.
      Parameters:
      value - The value being checked.
      Returns:
      true if the specified boolean is not null and is true.
    • join

      public static String join(Collection<?> tokens, char d)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static String join(Collection<?> tokens, String d)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static StringBuilder join(Collection<?> tokens, String d, StringBuilder sb)
      Joins the specified tokens into a delimited string and writes the output to the specified string builder.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      sb - The string builder to append the response to.
      Returns:
      The same string builder passed in as sb.
    • join

      public static String join(int[] tokens, char d)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static String join(List<?> tokens, char d)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static String join(List<?> tokens, String d)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static StringBuilder join(List<?> tokens, String d, StringBuilder sb)
      Joins the specified tokens into a delimited string and writes the output to the specified string builder.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      sb - The string builder to append the response to.
      Returns:
      The same string builder passed in as sb.
    • join

      public static String join(Object[] tokens, char d)
      Joins the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static StringBuilder join(Object[] tokens, char d, StringBuilder sb)
      Join the specified tokens into a delimited string and writes the output to the specified string builder.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      sb - The string builder to append the response to.
      Returns:
      The same string builder passed in as sb.
    • join

      public static String join(Object[] tokens, String separator)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      separator - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • joinnl

      public static String joinnl(Object[] tokens)
      Joins tokens with newlines.
      Parameters:
      tokens - The tokens to concatenate.
      Returns:
      A string with the specified tokens contatenated with newlines.
    • list

      @SafeVarargs public static <T> List<T> list(T... values)
      Shortcut for creating a modifiable list out of an array of values.
      Type Parameters:
      T - The element type.
      Parameters:
      values - The values to add to the list.
      Returns:
      A modifiable list containing the specified values.
    • listOfSize

      public static <E> ArrayList<E> listOfSize(int size)
      Convenience method for creating an ArrayList of the specified size.
      Type Parameters:
      E - The element type.
      Parameters:
      size - The initial size of the list.
      Returns:
      A new modifiable list.
    • map

      @SafeVarargs public static <K, V> LinkedHashMap<K,V> map(Object... values)
      Shortcut for creating a modifiable map out of an array of key-value pairs.
      Type Parameters:
      K - The key type.
      V - The value type.
      Parameters:
      values - The key-value pairs (alternating keys and values).
      Returns:
      A modifiable LinkedHashMap containing the specified key-value pairs.
    • n

      public static <T> T n(Class<T> type)
      Returns null for the specified type.
      Type Parameters:
      T - The type.
      Parameters:
      type - The type class.
      Returns:
      null.
    • na

      public static <T> T[] na(Class<T> type)
      Returns null for the specified array type.
      Type Parameters:
      T - The component type.
      Parameters:
      type - The component type class.
      Returns:
      null.
    • ne

      public static <T> boolean ne(T s1, T s2)
      Null-safe not-equals check.
      Type Parameters:
      T - The object type.
      Parameters:
      s1 - Object 1.
      s2 - Object 2.
      Returns:
      true if the objects are not equal.
    • ne

      public static <T, U> boolean ne(T o1, U o2, BiPredicate<T,U> test)
      Tests two objects for inequality, gracefully handling nulls.
      Type Parameters:
      T - Object 1 type.
      U - Object 2 type.
      Parameters:
      o1 - Object 1.
      o2 - Object 2.
      test - The test to use for equality.
      Returns:
      false if both objects are equal based on the test.
    • neic

      public static boolean neic(String s1, String s2)
      Tests two strings for non-equality ignoring case, but gracefully handles nulls.
      Parameters:
      s1 - String 1.
      s2 - String 2.
      Returns:
      true if the strings are not equal ignoring case.
    • nlist

      public static <T> List<T> nlist(Class<T> type)
      Returns a null list.
      Type Parameters:
      T - The element type.
      Parameters:
      type - The element type class.
      Returns:
      null.
    • nmap

      public static <K, V> Map<K,V> nmap(Class<K> keyType, Class<V> valueType)
      Returns a null map.
      Type Parameters:
      K - The key type.
      V - The value type.
      Parameters:
      keyType - The key type class.
      valueType - The value type class.
      Returns:
      null.
    • notContains

      public static boolean notContains(String s, char... values)
      Null-safe string not-contains operation.
      Parameters:
      s - The string to check.
      values - The characters to check for.
      Returns:
      true if the string does not contain any of the specified characters.
    • nullIfEmpty

      public static String nullIfEmpty(String value)
      Returns the specified string, or null if that string is null or empty.
      Parameters:
      value - The string value to check.
      Returns:
      The string value, or null if the string is null or empty.
    • nullIfEmpty3

      public static String nullIfEmpty3(String s)
      Returns null if the specified string is null or empty.
      Parameters:
      s - The string to check.
      Returns:
      null if the specified string is null or empty, or the same string if not.
    • obfuscate

      public static String obfuscate(String s)
      Returns an obfuscated version of the specified string.
      Parameters:
      s - The string to obfuscate.
      Returns:
      The obfuscated string with most characters replaced by asterisks.
    • opt

      public static final <T> Optional<T> opt(T t)
      Shortcut for calling Optional.ofNullable(Object).
      Type Parameters:
      T - The object type.
      Parameters:
      t - The object to wrap in an Optional.
      Returns:
      An Optional containing the specified object, or empty if null.
    • opte

      public static final <T> Optional<T> opte()
      Returns an empty Optional.
      Type Parameters:
      T - The object type.
      Returns:
      An empty Optional.
    • printLines

      public static final void printLines(String[] lines)
      Prints all the specified lines to System.out.
      Parameters:
      lines - The lines to print.
    • r

      public static String r(Object o)
      Converts an arbitrary object to a readable string format suitable for debugging and testing.

      This method provides intelligent formatting for various Java types, recursively processing nested structures to create human-readable representations. It's extensively used throughout the Juneau framework for test assertions and debugging output.

      Type-Specific Formatting:
      • null: Returns null
      • Optional: Recursively formats the contained value (or null if empty)
      • Collections: Formats as "[item1,item2,item3]" with comma-separated elements
      • Maps: Formats as "{key1=value1,key2=value2}" with comma-separated entries
      • Map.Entry: Formats as "key=value"
      • Arrays: Converts to list format "[item1,item2,item3]"
      • Iterables/Iterators/Enumerations: Converts to list and formats recursively
      • GregorianCalendar: Formats as ISO instant timestamp
      • Date: Formats as ISO instant string (e.g., "2023-12-25T10:30:00Z")
      • InputStream: Converts to hexadecimal representation
      • Reader: Reads content and returns as string
      • File: Reads file content and returns as string
      • byte[]: Converts to hexadecimal representation
      • Enum: Returns the enum name via Enum.name()
      • All other types: Uses Object.toString()
      Examples:

      // Collections r(List.of("a", "b", "c")) // Returns: "[a,b,c]" r(Set.of(1, 2, 3)) // Returns: "[1,2,3]" (order may vary) // Maps r(Map.of("foo", "bar", "baz", 123)) // Returns: "{foo=bar,baz=123}" // Arrays r(new int[]{1, 2, 3}) // Returns: "[1,2,3]" r(new String[]{"a", "b"}) // Returns: "[a,b]" // Nested structures r(List.of(Map.of("x", 1), Set.of("a", "b"))) // Returns: "[{x=1},[a,b]]" // Special types r(Optional.of("test")) // Returns: "test" r(Optional.empty()) // Returns: null r(new Date(1640995200000L)) // Returns: "2022-01-01T00:00:00Z" r(MyEnum.FOO) // Returns: "FOO"

      Recursive Processing:

      The method recursively processes nested structures, so complex objects containing collections, maps, and arrays are fully flattened into readable format. This makes it ideal for test assertions where you need to compare complex object structures.

      Error Handling:

      IO operations (reading files, streams) are wrapped in safe() calls, converting any exceptions to RuntimeExceptions. Binary data (InputStreams, byte arrays) is converted to hexadecimal representation for readability.

      Parameters:
      o - The object to convert to readable format. Can be null.
      Returns:
      A readable string representation of the object, or null if the input was null.
      See Also:
    • runtimeException

      public static RuntimeException runtimeException(String msg, Object... args)
      Creates a RuntimeException.
      Parameters:
      msg - The exception message.
      args - The arguments to substitute into the message.
      Returns:
      A new RuntimeException with the formatted message.
    • s

      public static String s(Object val)
      Shortcut for converting an object to a string.
      Parameters:
      val - The object to convert.
      Returns:
      The string representation of the object, or null if the object is null.
    • safe

      public static void safe(Snippet snippet)
      Runs a snippet of code and encapsulates any throwable inside a RuntimeException.
      Parameters:
      snippet - The snippet of code to run.
    • safe

      public static <T> T safe(ThrowingSupplier<T> s)
      Used to wrap code that returns a value but throws an exception. Useful in cases where you're trying to execute code in a fluent method call or are trying to eliminate untestable catch blocks in code.
      Type Parameters:
      T - The return type.
      Parameters:
      s - The supplier that may throw an exception.
      Returns:
      The result of the supplier execution.
    • safeSupplier

      public static <T> T safeSupplier(ThrowableUtils.SupplierWithThrowable<T> supplier)
      Allows you to wrap a supplier that throws an exception so that it can be used in a fluent interface.
      Type Parameters:
      T - The supplier type.
      Parameters:
      supplier - The supplier throwing an exception.
      Returns:
      The supplied result.
      Throws:
      RuntimeException - if supplier threw an exception.
    • set

      @SafeVarargs public static <T> LinkedHashSet<T> set(T... values)
      Shortcut for creating a modifiable set out of an array of values.
      Type Parameters:
      T - The element type.
      Parameters:
      values - The values to add to the set.
      Returns:
      A modifiable LinkedHashSet containing the specified values.
    • split

      public static List<String> split(String s)
      Splits a comma-delimited list into a list of strings.
      Parameters:
      s - The string to split.
      Returns:
      A list of split strings, or an empty list if the input is null.
    • split

      public static List<String> split(String s, char c)
      Splits a character-delimited string into a string array.

      Does not split on escaped-delimiters (e.g. "\,"); Resulting tokens are trimmed of whitespace.

      NOTE: This behavior is different than the Jakarta equivalent. split("a,b,c",',') -> {"a","b","c"} split("a, b ,c ",',') -> {"a","b","c"} split("a,,c",',') -> {"a","","c"} split(",,",',') -> {"","",""} split("",',') -> {} split(null,',') -> null split("a,b\,c,d", ',', false) -> {"a","b\,c","d"} split("a,b\\,c,d", ',', false) -> {"a","b\","c","d"} split("a,b\,c,d", ',', true) -> {"a","b,c","d"}

      Parameters:
      s - The string to split. Can be null.
      c - The character to split on.
      Returns:
      The tokens, or null if the string was null.
    • split

      public static void split(String s, char c, Consumer<String> consumer)
      Same as splita(String,char) but consumes the tokens instead of creating an array.
      Parameters:
      s - The string to split.
      c - The character to split on.
      consumer - The consumer of the tokens.
    • split

      public static List<String> split(String s, char c, int limit)
      Same as splita(String, char) but limits the number of tokens returned.
      Parameters:
      s - The string to split. Can be null.
      c - The character to split on.
      limit - The maximum number of tokens to return.
      Returns:
      The tokens, or null if the string was null.
    • split

      public static void split(String s, Consumer<String> consumer)
      Same as splita(String) but consumes the tokens instead of creating an array.
      Parameters:
      s - The string to split.
      consumer - The consumer of the tokens.
    • splita

      public static String[] splita(String s)
      Splits a comma-delimited list into an array of strings.
      Parameters:
      s - The string to split.
      Returns:
      An array of split strings.
    • splita

      public static String[] splita(String s, char c)
      Splits a character-delimited string into a string array.

      Does not split on escaped-delimiters (e.g. "\,"); Resulting tokens are trimmed of whitespace.

      NOTE: This behavior is different than the Jakarta equivalent. split("a,b,c",',') -> {"a","b","c"} split("a, b ,c ",',') -> {"a","b","c"} split("a,,c",',') -> {"a","","c"} split(",,",',') -> {"","",""} split("",',') -> {} split(null,',') -> null split("a,b\,c,d", ',', false) -> {"a","b\,c","d"} split("a,b\\,c,d", ',', false) -> {"a","b\","c","d"} split("a,b\,c,d", ',', true) -> {"a","b,c","d"}

      Parameters:
      s - The string to split. Can be null.
      c - The character to split on.
      Returns:
      The tokens, or null if the string was null.
    • splita

      public static String[] splita(String s, char c, int limit)
      Same as splita(String, char) but limits the number of tokens returned.
      Parameters:
      s - The string to split. Can be null.
      c - The character to split on.
      limit - The maximum number of tokens to return.
      Returns:
      The tokens, or null if the string was null.
    • splita

      public static String[] splita(String[] s, char c)
      Same as splita(String, char) except splits all strings in the input and returns a single result.
      Parameters:
      s - The string to split. Can be null.
      c - The character to split on.
      Returns:
      The tokens, or null if the input array was null
    • splitMap

      public static Map<String,String> splitMap(String s, boolean trim)
      Splits a list of key-value pairs into an ordered map.

      Example:

      String in = "foo=1;bar=2"; Map map = StringUtils.splitMap(in, ';', '=', true);

      Parameters:
      s - The string to split.
      trim - Trim strings after parsing.
      Returns:
      The parsed map, or null if the string was null.
    • splitMethodArgs

      public static String[] splitMethodArgs(String s)
      Splits the method arguments in the signature of a method.
      Parameters:
      s - The arguments to split.
      Returns:
      The split arguments, or null if the input string is null.
    • splitNested

      public static List<String> splitNested(String s)
      Splits a comma-delimited list containing "nesting constructs". Nesting constructs are simple embedded "{...}" comma-delimted lists. Example: "a{b,c},d" -> ["a{b,c}","d"] Handles escapes and trims whitespace from tokens.
      Parameters:
      s - The input string. The results, or null if the input was null.
      An empty string results in an empty array.
    • splitNestedInner

      public static List<String> splitNestedInner(String s)
      Splits a nested comma-delimited list. Nesting constructs are simple embedded "{...}" comma-delimted lists. Example: "a{b,c{d,e}}" -> ["b","c{d,e}"] Handles escapes and trims whitespace from tokens.
      Parameters:
      s - The input string. The results, or null if the input was null.
      An empty string results in an empty array.
    • splitQuoted

      public static String[] splitQuoted(String s)
      Splits a space-delimited string with optionally quoted arguments.

      Examples:

      • "foo" => ["foo"]
      • " foo " => ["foo"]
      • "foo bar baz" => ["foo","bar","baz"]
      • "foo 'bar baz'" => ["foo","bar baz"]
      • "foo \"bar baz\"" => ["foo","bar baz"]
      • "foo 'bar\'baz'" => ["foo","bar'baz"]
      Parameters:
      s - The input string.
      Returns:
      The results, or null if the input was null.
      An empty string results in an empty array.
    • splitQuoted

      public static String[] splitQuoted(String s, boolean keepQuotes)
      Same as splitQuoted(String) but allows you to optionally keep the quote characters.
      Parameters:
      s - The input string.
      keepQuotes - If true, quote characters are kept on the tokens.
      Returns:
      The results, or null if the input was null.
      An empty string results in an empty array.
    • toList

      public static final List<?> toList(Object o)
      Converts various collection-like objects to a List.

      This utility method enables testing of any collection-like object by converting it to a List that can be passed to methods such as TestUtils.assertList().

      Supported Input Types:
      • List: Returns the input unchanged
      • Iterable: Any collection, set, queue, etc. (converted to List preserving order)
      • Iterator: Converts iterator contents to List
      • Enumeration: Converts enumeration contents to List
      • Stream: Converts stream contents to List (stream is consumed)
      • Map: Converts map entries to List of Map.Entry objects
      • Array: Converts any array type (including primitive arrays) to List
      Usage Examples:

      // Test a Set Set<String> mySet = Set.of("a", "b", "c"); assertList(toList(mySet), "a", "b", "c"); // Test an array String[] myArray = {"x", "y", "z"}; assertList(toList(myArray), "x", "y", "z"); // Test a primitive array int[] numbers = {1, 2, 3}; assertList(toList(numbers), "1", "2", "3"); // Test a Stream Stream<String> myStream = Stream.of("foo", "bar"); assertList(toList(myStream), "foo", "bar"); // Test a Map (converted to entries) Map<String,Integer> myMap = Map.of("a", 1, "b", 2); assertList(toList(myMap), "a=1", "b=2"); // Test any Iterable collection Queue<String> myQueue = new LinkedList<>(List.of("first", "second")); assertList(toList(myQueue), "first", "second");

      Integration with Testing:

      This method is specifically designed to work with testing frameworks to provide a unified testing approach for all collection-like types. Instead of having separate assertion methods for arrays, sets, and other collections, you can convert them all to Lists and use standard list assertion methods.

      Parameters:
      o - The object to convert to a List. Must not be null and must be a supported collection-like type.
      Returns:
      A List containing the elements from the input object.
      Throws:
      IllegalArgumentException - if the input object cannot be converted to a List.
      See Also:
    • isConvertibleToList

      public static boolean isConvertibleToList(Object o)
    • toStream

      public static Stream<Object> toStream(Object array)
      Converts an array to a stream of objects.
      Parameters:
      array - The array to convert.
      Returns:
      A new stream.
    • traverse

      public static <T> void traverse(Object o, Consumer<T> c)
      Traverses all elements in the specified object and executes a consumer for it.
      Type Parameters:
      T - The element type.
      Parameters:
      o - The object to traverse.
      c - The consumer of the objects.
    • u

      public static <T> List<T> u(List<? extends T> value)
      Creates an unmodifiable view of the specified list.

      This is a null-safe wrapper around Collections.unmodifiableList(List).

      Type Parameters:
      T - The element type.
      Parameters:
      value - The list to make unmodifiable. Can be null.
      Returns:
      An unmodifiable view of the list, or null if the input was null.
    • u

      public static <K, V> Map<K,V> u(Map<? extends K,? extends V> value)
      Creates an unmodifiable view of the specified map.

      This is a null-safe wrapper around Collections.unmodifiableMap(Map).

      Type Parameters:
      K - The key type.
      V - The value type.
      Parameters:
      value - The map to make unmodifiable. Can be null.
      Returns:
      An unmodifiable view of the map, or null if the input was null.
    • u

      public static <T> Set<T> u(Set<? extends T> value)
      Creates an unmodifiable view of the specified set.

      This is a null-safe wrapper around Collections.unmodifiableSet(Set).

      Type Parameters:
      T - The element type.
      Parameters:
      value - The set to make unmodifiable. Can be null.
      Returns:
      An unmodifiable view of the set, or null if the input was null.
    • sb

      public static StringBuilder sb(String value)
      Helper method for creating StringBuilder objects.
      Parameters:
      value - The string value to wrap in a StringBuilder.
      Returns:
      A new StringBuilder containing the specified value.
    • classNameOf

      public static String classNameOf(Object o)
      Gets the fully qualified class name of the specified object.
      Parameters:
      o - The object to get the class name for.
      Returns:
      The fully qualified class name, or null if the object is null.
    • simpleClassNameOf

      public static String simpleClassNameOf(Object o)
      Gets the simple class name of the specified object.
      Parameters:
      o - The object to get the simple class name for.
      Returns:
      The simple class name, or null if the object is null.