Java: convert List to a String

前端 未结 22 2627
日久生厌
日久生厌 2020-11-22 01:03

JavaScript has Array.join()

js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve

Does Java have anything

22条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 01:46

    An orthodox way to achieve it, is by defining a new function:

    public static String join(String joinStr, String... strings) {
        if (strings == null || strings.length == 0) {
            return "";
        } else if (strings.length == 1) {
            return strings[0];
        } else {
            StringBuilder sb = new StringBuilder(strings.length * 1 + strings[0].length());
            sb.append(strings[0]);
            for (int i = 1; i < strings.length; i++) {
                sb.append(joinStr).append(strings[i]);
            }
            return sb.toString();
        }
    }
    

    Sample:

    String[] array = new String[] { "7, 7, 7", "Bill", "Bob", "Steve",
            "[Bill]", "1,2,3", "Apple ][","~,~" };
    
    String joined;
    joined = join(" and ","7, 7, 7", "Bill", "Bob", "Steve", "[Bill]", "1,2,3", "Apple ][","~,~");
    joined = join(" and ", array); // same result
    
    System.out.println(joined);
    

    Output:

    7, 7, 7 and Bill and Bob and Steve and [Bill] and 1,2,3 and Apple ][ and ~,~

提交回复
热议问题