java - How to join items of list, but use a different delimiter for the last item? -
given list like:
list<string> names = lists.newarraylist("george", "john", "paul", "ringo")
i'd transform string this:
george, john, paul , ringo
i can rather clumsy stringbuilder
thing so:
string namelist = names.stream().collect(joining(", ")); if (namelist.contains(",")) { stringbuilder builder = new stringbuilder(namelist); builder.replace(namelist.lastindexof(','), namelist.lastindexof(',') + 1, " and"); return builder.tostring(); }
is there bit more elegant approach? don't mind using library if needed.
notes:
- i use old
for
loop index, not looking such solution - there no commas within values (names)
as did of introduce second method "replacelast" not in jdk java.lang.string far:
import java.util.list; import java.util.stream.collectors; public final class stringutils { private static final string , = " , "; private static final string comma = ", "; // initial call wrapped replacelast call public static string asliteralnumeration(list<string> strings) { return replacelast(strings.stream().collect(collectors.joining(comma)), comma, and); } public static string replacelast(string text, string regex, string replacement) { return text.replacefirst("(?s)" + regex + "(?!.*?" + regex + ")", replacement); } }
you might change delimiters , params well. here test requirements far:
@org.junit.test public void test() { list<string> names = arrays.aslist("george", "john", "paul", "ringo"); assertequals("george, john, paul , ringo", stringutils.asliteralnumeration(names)); list<string> oneitemlist = arrays.aslist("paul"); assertequals("paul", stringutils.asliteralnumeration(oneitemlist)); list<string> emptylist = arrays.aslist(""); assertequals("", stringutils.asliteralnumeration(emptylist)); }
Comments
Post a Comment