What's the best way to build a string of delimited items in Java?

前端 未结 30 2228
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be i

30条回答
  •  长发绾君心
    2020-11-22 06:19

    You could write a little join-style utility method that works on java.util.Lists

    public static String join(List list, String delim) {
    
        StringBuilder sb = new StringBuilder();
    
        String loopDelim = "";
    
        for(String s : list) {
    
            sb.append(loopDelim);
            sb.append(s);            
    
            loopDelim = delim;
        }
    
        return sb.toString();
    }
    

    Then use it like so:

        List list = new ArrayList();
    
        if( condition )        list.add("elementName");
        if( anotherCondition ) list.add("anotherElementName");
    
        join(list, ",");
    

提交回复
热议问题