Java技巧 - 字符串拼接

一、测试用例:

    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        String result = join(list);
        System.out.println("拼接完成的字符串:"+ result);
    }

二、结果:

Java技巧 - 字符串拼接_第1张图片

三、封装方法:

1、普通方法

    public static String join(List list){
        StringBuilder builder = new StringBuilder();
        for(Integer sub: list) {
            builder.append(sub).append(",");
        }
        //处理末尾逗号
        return builder.substring(0, builder.length() - 1);
    }
    public static String join(List list) {
        StringBuilder builder = new StringBuilder();
        boolean first = true;
        for (Integer sub : list) {
            if (first) {
                first = false;
            } else {
                builder.append(",");
            }
            builder.append(sub);
        }
        return builder.toString();
    }

2、java.util.StringJoiner(jdk1.8提供)

    public static String join(List list) {
        StringJoiner joiner = new StringJoiner(",");
        for (Integer s : list) {
            joiner.add(String.valueOf(s));
        }
        return joiner.toString();
    }

3、流操作(jdk1.8提供)

   public static String join(List list) {
       return list.stream().map(String::valueOf).collect(Collectors.joining(","));
    }

4、guava joiner

pom引入jar包

 
            com.google.guava
            guava
            30.1.1-jre
            compile
        
  public static String join(List list) {
        return Joiner.on(",").join(list);
    }

你可能感兴趣的:(java技巧,java,开发语言,guava)