Pages

How to convert ArrayList to String in Java - Spring Example

Some time we need to convert ArrayList to String in Java
programming language in order to pass that String to stored procedure, any method
or any other program. Unfortunately Java
collection framework doesn't provide any direct utility method to convert ArrayList
to String
in Java. But Spring framework which is famous for dependency Injection and its
IOC container also provides API with common utilities like method to convert
Collection to String in Java. You can convert ArrayList to String using
Spring Framework's StringUtils class. StringUtils class
provide three methods to convert any collection e.g. ArrayList to String in Java,
as shown below:

By using above method you can convert ArrayList to comma separated
String, pipe separated String or you
can provide any other separator. You can also check How
to convert Collection to String for more examples of these methods.

That's all on How to convert
ArrayList to String in Java. We have seen in this Java program, how Spring's utility
method assist in converting ArrayList to delimited String in Java. If
you don't want to use Spring API and want to convert ArrayList
to String, you can use advanced for-each loop to create String
from ArrayList
as shown in below example :

Output:String created from ArrayList in Java using for-each loop : HashSet;LinkedList;Vector;

If you notice output, you will see
delimiter semicolon at the end also, which is unnecessary. you can remove that
using String's lastIndexOf() method or you can use traditional
for loop and not append delimiter after last element. Having said that, I
prefer Spring
framework to deal with such common things. If possible always use library
method like Spring to convert ArrayList
to String in Java.