Best Loop Idiom for special casing the last element

后端 未结 18 984
梦毁少年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 10:13

    I usually write a for loop like this:

    public static String forLoopConditional(String[] items) {
        StringBuilder builder = new StringBuilder();         
    
        builder.append("[");                                 
    
        for (int i = 0; i < items.length - 1; i++) {         
            builder.append(items[i] + ", ");                 
        }                                                    
    
        if (items.length > 0) {                              
            builder.append(items[items.length - 1]);         
        }                                                    
    
        builder.append("]");                                 
    
        return builder.toString();                           
    }       
    

提交回复
热议问题