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


    转自 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),使得代码很难看。

  • 相关阅读:
    第十二节:WebApi自动生成在线Api文档的两种方式
    第十一节:WebApi的版本管理的几种方式
    自学Python1.3-centos内python3并与python2共存
    自学Python1.2-环境的搭建:Pycharm及python安装详细教程
    自学Python1.1-简介
    Java通过ftp上传文件
    Java使用Spring初识
    Java中类似C#中Task.wait()的类CountDownLatch
    Java创建多线程和线程安全集合Vector
    未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项。试图加载格式不正确的程序。
  • 原文地址:https://www.cnblogs.com/xing-nb/p/12163150.html
Copyright © 2020-2023  润新知