JavaScript has Array.join()
js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve
Does Java have anything
I wrote this one (I use it for beans and exploit toString
, so don't write Collection
):
public static String join(Collection> col, String delim) {
StringBuilder sb = new StringBuilder();
Iterator> iter = col.iterator();
if (iter.hasNext())
sb.append(iter.next().toString());
while (iter.hasNext()) {
sb.append(delim);
sb.append(iter.next().toString());
}
return sb.toString();
}
but Collection
isn't supported by JSP, so for TLD I wrote:
public static String join(List> list, String delim) {
int len = list.size();
if (len == 0)
return "";
StringBuilder sb = new StringBuilder(list.get(0).toString());
for (int i = 1; i < len; i++) {
sb.append(delim);
sb.append(list.get(i).toString());
}
return sb.toString();
}
and put to .tld
file:
join
com.core.util.ReportUtil
java.lang.String join(java.util.List, java.lang.String)
and use it in JSP files as:
<%@taglib prefix="funnyFmt" uri="tag:com.core.util,2013:funnyFmt"%>
${funnyFmt:join(books, ", ")}