Use one of the the StringUtils.join methods in Apache Commons Lang.
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.join(list, ", ");
If you are fortunate enough to be using Java 8, then it's even easier...just use String.join
String result = String.join(", ", list);
Answer from Jeff Olson on Stack OverflowUse one of the the StringUtils.join methods in Apache Commons Lang.
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.join(list, ", ");
If you are fortunate enough to be using Java 8, then it's even easier...just use String.join
String result = String.join(", ", list);
Using Java 8+
String str = list.stream().collect(Collectors.joining())
or even
String str = String.join("", list); // Substitute "" with your desired separator.
String.join
With Java 8 you can do this without any third party library.
If you want to join a Collection of Strings you can use the String.join() method:
List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
Collectors.joining
If you have a Collection with another type than String you can use the Stream API with the joining Collector:
List<Person> list = Arrays.asList(
new Person("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);
String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(", ")); // "John, Anna, Paul"
The StringJoiner class may also be useful.
All the references to Apache Commons are fine (and that is what most people use) but I think the Guava equivalent, Joiner, has a much nicer API.
You can do the simple join case with
Joiner.on(" and ").join(names)
but also easily deal with nulls:
Joiner.on(" and ").skipNulls().join(names);
or
Joiner.on(" and ").useForNull("[unknown]").join(names);
and (useful enough as far as I'm concerned to use it in preference to commons-lang), the ability to deal with Maps:
Map<String, Integer> ages = .....;
String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
// Outputs:
// Bill is 25, Joe is 30, Betty is 35
which is extremely useful for debugging etc.