Converting a List to String in Java

1. Introduction

In this quick article, we’ll have a look at how to convert a List of elements to a String. This might be useful in certain scenarios like printing the contents to the console in a human-readable form for inspection/debugging.

2. Standard toString() on a List

One of the simplest ways is to simply call the toString() method on the List:

@Test
public void whenListToString_thenPrintDefault() {
    List<Integer> intLIst = Arrays.asList(1, 2, 3);
 
    System.out.println(intLIst);
}

Output:

[1, 2, 3]

This technique internally utilizes the toString() method of the type of the elements within the List. In our case, we are using the Integer type which has a proper implementation of the toString() method.

If we are using our custom type, say, Person, then we need to make sure that the Person class overrides the toString() method and does not rely on the default implementation. If the toString() method is not properly implemented, you might get unexpected results:

[org.baeldung.java.lists.ListToSTring$Person@1edf1c96,
  org.baeldung.java.lists.ListToSTring$Person@368102c8,
  org.baeldung.java.lists.ListToSTring$Person@6996db8]

3. Custom Implementation Using Collectors

Often, we might need to display the output in a different format.

Compared to the previous example, let’s replace the comma (,) with a hyphen (-) and the square brackets ([, ]) with a set of curly braces ({, }):

@Test
public void whenCollectorsJoining_thenPrintCustom() {
    List<Integer> intList = Arrays.asList(1, 2, 3);
    String result = intList.stream()
      .map(n -> String.valueOf(n))
      .collect(Collectors.joining("-", "{", "}"));
 
    System.out.println(result);
}

Output:

{1-2-3}

The Collectors.joining() method requires a CharSequence, so we need to map the Integer to String. The same idea can be utilized in case of any other class even when we do not have the access to the code of that class.

4. Using an External Library

We’ll now see the usage of Apache Commons’ StringUtils class to achieve the similar results.

4.1. Maven Dependency

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

The latest version of the dependency can be found here.

4.2. Implementation

The implementation is literally a single method call:

@Test
public void whenStringUtilsJoin_thenPrintCustom() {
    List<Integer> intList = Arrays.asList(1, 2, 3);
 
    System.out.println(StringUtils.join(intList, "|"));
}

Output:

1|2|3

Again, this implementation is internally dependent on the toString() implementation of the type we are considering.

5. Conclusion

In this article, we saw how easy it is to convert a List to a String using different techniques.

As always, the full source code for this article can be found over on GitHub.

Related posts:

Convert Time to Milliseconds in Java
Spring Boot - Google Cloud Platform
Java Program to Check Whether Topological Sorting can be Performed in a Graph
Java Optional as Return Type
Spring Boot - Application Properties
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Java Program to Implement Graph Coloring Algorithm
A Guide to WatchService in Java NIO2
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Java Program to Implement LinkedHashSet API
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Python String lstrip()
A Guide to Apache Commons Collections CollectionUtils
Guide to Java OutputStream
Java Program to Perform Left Rotation on a Binary Search Tree
Call Methods at Runtime Using Java Reflection
HashMap trong Java hoạt động như thế nào?
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Using a List of Values in a JdbcTemplate IN Clause
Python Program to Check If a String Is a Number (Float)
An Intro to Spring Cloud Vault
HTTP Authentification and CGI/Servlet
Java Program to Construct an Expression Tree for an Infix Expression
Creating a Web Application with Spring 5
Java Program to Implement Sparse Array
Java Multi-line String
Lập trình đa luồng trong Java (Java Multi-threading)
Serve Static Resources with Spring
Java Program to implement Associate Array
The Order of Tests in JUnit