Generic Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this article, we will look into the different ways we can convert a given ArrayList<Object> to an ArrayList<String>.

2. Problem Statement

Let's understand the problem statement here. Suppose we have an ArrayList<Object> where the objects can be of any type, ranging from auto-boxed primitive types such as Integer, Float, or Boolean, to non-primitive reference types such as String, ArrayList, HashMap, or even custom-defined classes. We have to write code to convert the said list into an ArrayList<String>. Let's look at a few examples:

Example 1: [1, 2, 3, 4, 5]
Output 1: ["1", "2", "3", "4", "5"]

Example 2: ["Hello", 4.9837, -19837338737, true]
Output 2: ["Hello", "4.9837", "-19837338737", "true"]

Example 3: [new Node(1,4), new Double(7699.05), new User("John Doe")]
Output 3: ["Node (x=1, y=4)", "7699.05", "User (full name=John Doe)"]

We can provide a host of different objects in the input list, including objects of custom-defined classes like User and Node shown below. It is assumed that these classes have an overridden toString() method. In case the method is not defined, the Object class's toString() will be invoked, which will generate an output like:

[email protected], [email protected]

The above examples contain instances of custom-defined classes such as User and Node:

public class User {
    private final String fullName;

    // getters and setters

   @Override
    public String toString() {
        return "User (" + "full name='" + fullName + ')';
    }
}
public class Node {
    private final int x;
    private final int y;

    // getters and setters

    @Override
    public String toString() {
        return "Node (" + "x=" + x + ", y=" + y + ')';
    }
}

Finally, let's assume that in the remaining sections, the variables inputList and expectedStringList contain a reference to our desired input and output lists:

List<Object> inputList = List.of(
                        1,
                        true,
                        "hello",
                        Double.valueOf(273773.98),
                        new Node(2, 4),
                        new User("John Doe")
                    );
List<String> expectedStringList = List.of(
                        "1",
                        "true",
                        "hello",
                        Double.toString(273773.98),
                        new Node(2, 4).toString(),
                        new User("John Doe").toString()
                    );

3. Conversion Using Java Collections For-Each Loop

Let's try to use Java Collections to solve our problem. The idea is to iterate through the elements of the list and convert each element into a String. Once done, we have a list of String objects. In the following code, we iterate through the given list using a for-each loop and explicitly convert every object to a String by calling toString() on it:

List<String> outputList = new ArrayList<>(inputList.size());
for(Object obj : inputList){
    outputList.add(obj.toString());
}
Assert.assertEquals(expectedStringList, outputList);

This solution works for all combinations of objects in the input list and works on all Java versions above Java 5. However, the above solution is not immune to null objects in the input and will throw a NullPointerException whenever it encounters a null. A simple enhancement utilizes the toString() method provided by the Objects utility class introduced in Java 7 and is null-safe:

List<String> outputList = new ArrayList<>(inputList.size());
for(Object obj : inputList){
    outputList.add(Objects.toString(obj, null));
}
Assert.assertEquals(expectedStringList, outputList);

4. Conversion Using Java Streams

We can leverage the Java Streams API to solve our problem as well. We first convert the inputList, our data source, to a stream by applying the stream() method. Once we have a stream of elements, which are of type Object, we need an intermediate operation, which in our case is to do the object-to-string conversion, and finally, a terminal operation, which is to collect the results into another list of type String.

The intermediate operation in our case is a map() operation that takes a lambda expression:

(obj) -> Objects.toString(obj, null)

Finally, our stream needs a terminal operation to compile and return the desired list. In the subsequent subsections, we discuss the different terminal operations available at our disposal.

4.1. Collectors.toList() as a Terminal Operation

In this approach, we use Collectors.toList() to collect the stream generated by the intermediate operation into an output list:

List<String> outputList;
outputList = inputList
    .stream()
    .map((obj) -> Objects.toString(obj, null))
    .collect(Collectors.toList());
Assert.assertEquals(expectedStringList, outputList);

This approach works well for Java 8 and above as the Streams API was introduced in Java 8. The list produced as output here is a mutable list, which means we can add elements to it. The output list can contain null values as well.

4.2. Collectors.toUnmodifableList() as a Terminal Operation – Java 10 Compatible Approach

If we want to produce an output list of String objects that is unmodifiable, we can leverage the Collectors.toUnmodifableList() implementation introduced in Java 10:

List<String> outputList;
outputList = inputList
    .stream()
    .filter(Objects::nonNull)
    .map((obj) -> Objects.toString(obj, null))
    .collect(Collectors.toUnmodifiableList());
Assert.assertEquals(expectedStringListWithoutNull, outputList);

An important caveat here is that the list cannot contain null values and, hence, if the inputList contains a null, this code produces a NullPointerException. This is why we add a filter to select only nonNull elements from the stream before applying our operation. The outputList is immutable and will produce an UnsupportedOperationException if there is an attempt to modify it later.

4.3. toList() as a Terminal Operation – Java 16 Compatible Approach

In case we want to directly create an unmodifiable list from the input Stream, but we want to allow null values in the resulting list, we can use the toList() method that was introduced in the Stream interface in Java 16:

List<String> outputList;
outputList = inputList
    .stream()
    .map((obj) -> Objects.toString(obj, null))
    .toList();
Assert.assertEquals(expectedStringList, outputList);

5. Conversion Using Guava

We can use the Google Guava Library to transform the input list of objects into a new list of String.

5.1. Maven Configuration

To use the Google Guava library, we need to include the corresponding Maven dependency in pom.xml:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
    <scope>test</scope>
</dependency>

The latest version of the dependency can be obtained from Maven Central.

5.2 Using Lists.transform()

We can use the transform() method in the Google Guava Lists class. It takes in the inputList and the aforementioned lambda expression to generate the outputList of String objects:

List<String> outputList;
outputList = Lists.transform(inputList, obj -> Objects.toString(obj, null));
Assert.assertEquals(expectedStringList, outputList);

With this method, the output list can contain null values.

6. Conclusion

In this article, we looked into a few different ways an ArrayList of Object elements can be converted into an ArrayList of String. We explored different implementations from a for-each loop-based approach to a Java Streams-based approach. We also looked at different implementations specific to different Java versions, as well as one from Guava. As usual, all code samples can be found over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments