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:

Java CyclicBarrier vs CountDownLatch
Merging Two Maps with Java 8
Java Program to Implement Flood Fill Algorithm
Implementing a Binary Tree in Java
Java Program to Implement Kosaraju Algorithm
Working with Kotlin and JPA
DistinctBy in the Java Stream API
Java Program to Implement Floyd Cycle Algorithm
Spring Boot Configuration with Jasypt
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
How to Get a Name of a Method Being Executed?
A Guide to JPA with Spring
Spring Boot - Thymeleaf
Java Program to Find the Longest Path in a DAG
Convert String to int or Integer in Java
Java Program to Implement Strassen Algorithm
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Lớp Arrarys trong Java (Arrays Utility Class)
Generate a String
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Python String swapcase()
Java Program to Construct an Expression Tree for an Postfix Expression
Python String isupper()
Java Program to Implement Circular Singly Linked List
Java Program to Create the Prufer Code for a Tree
Apache Tiles Integration with Spring MVC
Java Program to find the maximum subarray sum using Binary Search approach
Lập trình đa luồng với CompletableFuture trong Java 8
Java Program to Implement Double Order Traversal of a Binary Tree