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

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

    I would use Google Collections. There is a nice Join facility.
    http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html

    But if I wanted to write it on my own,

    package util;
    
    import java.util.ArrayList;
    import java.util.Iterable;
    import java.util.Collections;
    import java.util.Iterator;
    
    public class Utils {
        // accept a collection of objects, since all objects have toString()
        public static String join(String delimiter, Iterable objs) {
            if (objs.isEmpty()) {
                return "";
            }
            Iterator iter = objs.iterator();
            StringBuilder buffer = new StringBuilder();
            buffer.append(iter.next());
            while (iter.hasNext()) {
                buffer.append(delimiter).append(iter.next());
            }
            return buffer.toString();
        }
    
        // for convenience
        public static String join(String delimiter, Object... objs) {
            ArrayList list = new ArrayList();
            Collections.addAll(list, objs);
            return join(delimiter, list);
        }
    }
    
    
    

    I think it works better with an object collection, since now you don't have to convert your objects to strings before you join them.

    提交回复
    热议问题