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

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

    And a minimal one (if you don't want to include Apache Commons or Gauva into project dependencies just for the sake of joining strings)

    /**
     *
     * @param delim : String that should be kept in between the parts
     * @param parts : parts that needs to be joined
     * @return  a String that's formed by joining the parts
     */
    private static final String join(String delim, String... parts) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < parts.length - 1; i++) {
            builder.append(parts[i]).append(delim);
        }
        if(parts.length > 0){
            builder.append(parts[parts.length - 1]);
        }
        return builder.toString();
    }
    

提交回复
热议问题