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

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

    Pre Java 8:

    Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby:

    StringUtils.join(java.lang.Iterable,char)


    Java 8:

    Java 8 provides joining out of the box via StringJoiner and String.join(). The snippets below show how you can use them:

    StringJoiner

    StringJoiner joiner = new StringJoiner(",");
    joiner.add("01").add("02").add("03");
    String joinedString = joiner.toString(); // "01,02,03"
    

    String.join(CharSequence delimiter, CharSequence... elements))

    String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"
    

    String.join(CharSequence delimiter, Iterable elements)

    List strings = new LinkedList<>();
    strings.add("Java");strings.add("is");
    strings.add("cool");
    String message = String.join(" ", strings);
    //message returned is: "Java is cool"
    

提交回复
热议问题