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

前端 未结 30 2244
耶瑟儿~
耶瑟儿~ 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:35

    Use StringBuilder and class Separator

    StringBuilder buf = new StringBuilder();
    Separator sep = new Separator(", ");
    for (String each : list) {
        buf.append(sep).append(each);
    }
    

    Separator wraps a delimiter. The delimiter is returned by Separator's toString method, unless on the first call which returns the empty string!

    Source code for class Separator

    public class Separator {
    
        private boolean skipFirst;
        private final String value;
    
        public Separator() {
            this(", ");
        }
    
        public Separator(String value) {
            this.value = value;
            this.skipFirst = true;
        }
    
        public void reset() {
            skipFirst = true;
        }
    
        public String toString() {
            String sep = skipFirst ? "" : value;
            skipFirst = false;
            return sep;
        }
    
    }
    

提交回复
热议问题