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

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

    You can generalize it, but there's no join in Java, as you well say.

    This might work better.

    public static String join(Iterable s, String delimiter) {
        Iterator iter = s.iterator();
        if (!iter.hasNext()) return "";
        StringBuilder buffer = new StringBuilder(iter.next());
        while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
        return buffer.toString();
    }
    

提交回复
热议问题