当前位置首页 > Apache知识

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

阅读次数:270 次  来源:admin  发布时间:

转自 http://my.oschina.net/zenglingfan/blog/134872

写代码的时候,经常会碰到需要把一个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),使得代码很难看。

上一篇:解决Ubuntu开机Waitingfor60secondsmorefornetworkconfiguration
下一篇:安装debian总结以及编译linux内核