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:

public static String collectionToCommaDelimitedString(Collection coll)
public static String collectionToDelimitedString(Collection coll, String delim)
public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix)

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.


package test;

import java.util.ArrayList;
import org.springframework.util.StringUtils;

/**
 *
 * Java program to convert ArrayList to String in Java using Spring framework.
 * It uses Spring's StringUtils class to create String from ArrayList in Java
 * @author
 */
public class ArrayListProgram {

 
 public static void main(String args[]) {

 // ArrayList to be converted into String
 ArrayList<String> language = new ArrayList<String>();
        language.add("Java");
        language.add("C++");
        language.add("Scala");
 
 // Converting ArrayList to String using Spring API , result is comma separated String      
 String arraylistToString = StringUtils.collectionToCommaDelimitedString(language);
 
 System.out.println("String converted from ArrayList : " + arraylistToString);
 
 //If you want to use separater other than coma while converting ArrayList to String use below method
 String pipeSeparated = StringUtils.collectionToDelimitedString(language, "|");
 
 System.out.println("PIPE delimited String from ArrayList : " + pipeSeparated);
 
 //Let's generate colon delimited String from ArrayList
 
 String colonSeparated = StringUtils.collectionToDelimitedString(language, ":");
 System.out.println("Colon separated String from ArrayList : " + colonSeparated);
 }
}

Output:


String converted from ArrayList : Java,C++,Scala
PIPE delimited String from ArrayList : Java|C++|Scala
Colon separated String from ArrayList : Java:C++:Scala


That's all on