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

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

    in Java 8 you can do this like:

    list.stream().map(Object::toString)
            .collect(Collectors.joining(delimiter));
    

    if list has nulls you can use:

    list.stream().map(String::valueOf)
            .collect(Collectors.joining(delimiter))
    

    it also supports prefix and suffix:

    list.stream().map(String::valueOf)
            .collect(Collectors.joining(delimiter, prefix, suffix));
    

提交回复
热议问题