How do I join an array or collection of Strings into a single String?
Author: Deron Eriksson
Description: This Java example shows how to join an array or collection of Strings into a single String.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
The StringUtils class of the Commons LangS library has several join() methods that can be used to combine an array or collection of strings into a single string. The JoinTest class demonstrates this first for an array of strings. After displaying join() results for the array, it converts this array of strings to a list of strings and then displays join() results for this list. JoinTest.javapackage test; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.commons.lang.StringUtils; public class JoinTest { public static void main(String[] args) throws IOException { String[] strArray = { "string1", "string2", "string3" }; System.out.println("Joining array of strings"); System.out.println(StringUtils.join(strArray)); System.out.println(StringUtils.join(strArray, " ")); System.out.println("\nJoining list of strings"); List<String> strList = Arrays.asList(strArray); System.out.println(StringUtils.join(strList, null)); System.out.println(StringUtils.join(strList, " ")); } } The output of JoinTest is displayed here: ResultsJoining array of strings string1string2string3 string1 string2 string3 Joining list of strings string1string2string3 string1 string2 string3 |