Java: convert List to a String

前端 未结 22 2582
日久生厌
日久生厌 2020-11-22 01:03

JavaScript has Array.join()

js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve

Does Java have anything

22条回答
  •  北海茫月
    2020-11-22 01:37

    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, ", ")}
    

提交回复
热议问题