Given a list
List l = new ArrayList();
l.add(\"one\");
l.add(\"two\");
l.add(\"three\");
I have a method
<What about join from: org.apache.commons.lang.StringUtils
Example:
StringUtils.join(new String[] { "one", "two", "three" }, ", "); // one, two, three
To have "and" or ", and" you can simple replace the last comma.
Other answers talk about "replacing the last comma", which isn't safe in case the last term itself contains a comma.
Rather than use a library, you can just use one (albeit long) line of JDK code:
public static String join(List<String> msgs) {
return msgs == null || msgs.size() == 0 ? "" : msgs.size() == 1 ? msgs.get(0) : msgs.subList(0, msgs.size() - 1).toString().replaceAll("^.|.$", "") + " and " + msgs.get(msgs.size() - 1);
}
See a live demo of this code handling all edge cases.
FYI, here's a more readable two-liner:
public static String join(List<String> msgs) {
int size = msgs == null ? 0 : msgs.size();
return size == 0 ? "" : size == 1 ? msgs.get(0) : msgs.subList(0, --size).toString().replaceAll("^.|.$", "") + " and " + msgs.get(size);
}