Java Convert Array of Objects to Array of Strings using Apache Commons Lang

Tags: ArrayUtils Apache Commons Apache Commons Lang array String Convert

In this Java tutorial we learn how to convert an array of object values into an array of String values using the ArrayUtils class of Apache Commons Lang library.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to Convert an Object Array to String Array in Java

The Apache Commons Lang library provides the method ArrayUtils.toStringArray() to convert an array of objects to an array of String representation of each object value.

You can learn how to use the ArrayUtils.toStringArray() method in the below example code.

ConvertToStringArrayExample1.java

import org.apache.commons.lang3.ArrayUtils;

public class ConvertToStringArrayExample1 {
    public static void main(String... args) {
        Integer[] arr = new Integer[] { 1, 2, 3, 4};

        String[] result = ArrayUtils.toStringArray(arr);

        for(String value: result) {
            System.out.println(value);
        }
    }
}
The output is:
1
2
3
4

And with an array containing null values, we can provide the value to represent null value in the new array.

ConvertToStringArrayExample2.java

import org.apache.commons.lang3.ArrayUtils;

public class ConvertToStringArrayExample2 {
    public static void main(String... args) {
        Integer[] arr = new Integer[] { 1, 2, 3, null, 4};

        String[] result = ArrayUtils.toStringArray(arr, "NULL VALUE");

        for(String value: result) {
            System.out.println(value);
        }
    }
}
The output is:
1
2
3
NULL VALUE
4

Happy Coding 😊