I'm looking for something to augment the function of the apache commons join() function, basically that will do what makePrettyList() does
public String makePrettyList(List<String> items) {
String list = org.apache.commons.lang.StringUtils.join(items, ", ");
int finalComma = list.lastIndexOf(",");
return list.substring(0, finalComma) + " and" + list.substring(finalComma + 1, list.length());
}
makePrettyList(["Alpha", "Beta", "Omega"]) --> "Alpha, Beta and Omega"
[Didn't handle trailing and leading nulls/empties gracefully. Now works better.]
My take on it, using Google Guava (not official Java, but a darn good set of packages). I'm offering it since it appears that you looked at using Joiner, but then rejected it. So since you were open to using Joiner at one point, maybe you want to look at it again:
And the test driver:
And the output:
null
null
a
a and b
a, b, c, and d
a, b, c, and d
a, b, and c
a, b, and c
a, b, and c
a, b, and c
I like this because it doesn't do any string splicing. It partitions the provided list of strings, and then correctly glues them together, using rules based on the number of string elements, without going back and backfitting an "and" after the fact. I also handle all sorts of edge cases for nulls/empties appearing at the beginning, end, or middle of the list of strings. It might be that you're guaranteed that this won't happen, so you can simplify this solution.
[Mine is a bit different from yours in that when I have exactly two elements, I don't put a comma after the first element and before the "and", while for three or more, there is a comma before the "and". It's a style thing. Easy to adjust to whatever you prefer with regards to how commas ought to work.]