Best Loop Idiom for special casing the last element

后端 未结 18 1032
梦毁少年i
梦毁少年i 2020-12-23 09:25

I run into this case a lot of times when doing simple text processing and print statements where I am looping over a collection and I want to special case the last element (

18条回答
  •  渐次进展
    2020-12-23 09:56

    A third alternative is the following

    StringBuilder output = new StringBuilder();
    for (int i = 0; i < items.length - 1; i++) {
        output.append(items[i]);
        output.append(",");
    }
    if (items.length > 0) output.append(items[items.length - 1]);
    

    But the best is to use a join()-like method. For Java there's a String.join in third party libraries, that way your code becomes:

    StringUtils.join(items,',');
    

    FWIW, the join() method (line 3232 onwards) in Apache Commons does use an if within a loop though:

    public static String join(Object[] array, char separator, int startIndex, int endIndex)     {
            if (array == null) {
                return null;
            }
            int bufSize = (endIndex - startIndex);
            if (bufSize <= 0) {
                return EMPTY;
            }
    
            bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1);
            StringBuilder buf = new StringBuilder(bufSize);
    
            for (int i = startIndex; i < endIndex; i++) {
                if (i > startIndex) {
                    buf.append(separator);
                }
                if (array[i] != null) {
                    buf.append(array[i]);
                }
            }
            return buf.toString();
        }
    

提交回复
热议问题