https://www.baeldung.com/java-list-to-string
1. Introduction
In this quick tutorial, we’ll explain how to convert a List of elements to a String. This can 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 call the toString() method on the List:
Output:
[1, 2, 3]
This technique internally utilizes the toString() method of the type of elements within the List. In our case, we’re using the Integer type, which has a proper implementation of the toString() method.
If we’re using our custom type, such as Person, then we need to make sure that the Person class overrides the toString() method and doesn’t rely on the default implementation. If we don’t properly implement the toString() method, we 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 ({, }):
Output:
{1-2-3}
The Collectors.joining() method requires a CharSequence, so we need to map the Integer to String. We can utilize this same idea with other classes, even when we don’t have access to the code of the class.
4. Using an External Library
Now we’ll use Apache Commons’ StringUtils class to achieve similar results.
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>3.11version>
dependency>
The implementation is literally a single method call:
Output:
1|2|3
Again, this implementation is internally dependent on the toString() implementation of the type we’re considering.
5. Conclusion
In this article, we learned how easy it is to convert a List to a String using different techniques.
Original: https://www.cnblogs.com/kungfupanda/p/15725833.html
Author: 功夫 熊猫
Title: Converting a List to String in Java
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/537014/
转载文章受原作者版权保护。转载请注明原作者出处!