org.apache.commons.lang.StringUtils 中 Join 函數

寫代碼的時候,經常會碰到需要把一個List中的每個元素,按逗號分隔轉成字符串的需求,以前是自己寫一段比較難看的代碼,先把字符串拼出來,再把最後面多餘的逗號去掉;雖然功能可以實現,但總覺得最後加的那一步操作很沒有必要:

public static String join(List<String> list, String seperator){
    if(list.isEmpty()){
        return "";
    }
    
    StringBuffer sb = new StringBuffer();
    
    for(int i=0; i<list.size(); i++){
        sb.append(list.get(i)).append(seperator);
    }
    
    return sb.substring(0, sb.length() - seperator.length());
}

 

轉到java後,一直不知道有org.apache.commons.lang 這麼一個包,裏面提供了功能強大的join函數,直到有一次看到同事在用……

看了一下源代碼,實現的思路比較精巧,巧妙避免了像我在上面,總是需要最後再取一次substring的問題,org.apache.commons.lang.StringUtils 中 join函數代碼如下:

/**
     * <p>Joins the elements of the provided array into a single String
     * containing the provided list of elements.</p>
     *
     * <p>No delimiter is added before or after the list.
     * Null objects or empty strings within the array are represented by
     * empty strings.</p>
     *
     * <pre>
     * StringUtils.join(null, *)               = null
     * StringUtils.join([], *)                 = ""
     * StringUtils.join([null], *)             = ""
     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
     * StringUtils.join(["a", "b", "c"], null) = "abc"
     * StringUtils.join([null, "", "a"], ';')  = ";;a"
     * </pre>
     *
     * @param array  the array of values to join together, may be null
     * @param separator  the separator character to use
     * @param startIndex the first index to start joining from.  It is
     * an error to pass in an end index past the end of the array
     * @param endIndex the index to stop joining from (exclusive). It is
     * an error to pass in an end index past the end of the array
     * @return the joined String, {@code null} if null array input
     * @since 2.0
     */
    public static String join(Object[] array, char separator, int startIndex, int endIndex) {
        if (array == null) {
            return null;
        }
        int noOfItems = endIndex - startIndex;
        if (noOfItems <= 0) {
            return EMPTY;
        }
        
        StringBuilder buf = new StringBuilder(noOfItems * 16);

        for (int i = startIndex; i < endIndex; i++) {
            if (i > startIndex) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }

以上代碼精髓在於這一句

if (i > startIndex) {
    buf.append(separator);
}

 

保證了第一次不會插入 separator,而後面插入的 separator 又都是在 array 的 value 之前,這樣最後就不會多出一個 separator.

自己的代碼主要是沒想到 StringBuilder 直接用 toString 得到結果,所以以前總是不能直接在 for 循環裏做完,出來還要做一次(還要計算各種length),使得代碼很難看。

發佈了0 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章