How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through loop and create a big String where individual String are separated by delimiter, you still need to handle cases like last element should not have delimiter or at bare minimum you need to test that code. I like Joshua Bloach advise on Effective Java to use libraries for those common task let it be internal proprietary library or any open source library as used in previous examples of Spring, Apache Commons or Google’s Guava but point is that you should avoid converting ArrayList to String like common task by yourself on application code.
Collection to String Example in Java
I am big fan on Spring framework and we use Spring in most of our projects and we have already discussed few examples of Spring framework in Java before e.g. Using Spring to calculate execution time and Spring security to control Concurrent Sessions in Java. In this Java tutorial I will share you an example of converting List to delimited String, Set to delimit String or any other Collection class into delimited String by using Spring framework's StringUtils class. Spring provides two convenient method collectionToCommaDelimitedString and collectionToDelimitedString which can be used here. This example is general and you can convert any Collection into comma separated or any delimiter separated String by using this technique. Order of individual String in delimited String is the order on which they are stored in Collection e.g. List or Set. This particular Java program shows How to convert a List into comma, colon and pipe separated String.
That’s all on How to convert Collection into Comma or delimiter separated String in Java. In this Java tutorial we have seen How to convert List into comma separated, colon separate and finally PIPE separated String. You can use any delimiter of your choice to print all Collection elements as String in Java.
Other Java Collection tutorials from Javarevisited Blog