Converting a List to String in Java
1. Introduction
2. Standard toString() on a 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:
[[email protected],
[email protected],
[email protected]]
3. Custom Implementation Using Collectors
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
4.1. Maven Dependency
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency>
The latest version of the dependency can be found here.
4.2. Implementation
@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
As always, the full source code for this article can be found over on GitHub.