优雅的用符号拼接list中的元素

参考Android SDK 中 TextUtil.join方法, 加入泛型, 方便用户指定要拼接的是对象中的哪个字段.

public static void main(String[] args) {

    ArrayList arrayList = new ArrayList<>();
    arrayList.add(new Data("是"));
    arrayList.add(new Data("的"));
    arrayList.add(new Data("订单"));
    arrayList.add(new Data("试试"));

    //传统写法
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < arrayList.size() ; i++) {
        stringBuilder.append(arrayList.get(i).a+",");
    }
    System.out.println( "gaom s1="+stringBuilder.substring(0,stringBuilder.toString().lastIndexOf(",")));

    //用法1 不用泛型 , 强转
    String joinS = join("|", arrayList, new IKey() {
        @Override
        public String getKey(Object o) {
            return ((Data) o).a;
        }
    });

    //用法2  用泛型
    String joins = join(",", arrayList, new IKey() {
        @Override
        public String getKey(Data o) {
            return o.a;
        }
    });
    System.out.println( "gaom s3="+joinS);
    System.out.println( "gaom s2="+joins);
}

public static class Data {
    public String a;

    public Data(String a) {
        this.a = a;
    }
}

public interface IKey {
    String getKey(T t);
}

public static  String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens) {
   return join(delimiter, tokens, new IKey() {
        @Override
        public String getKey(Object o) {
            return o.toString();
        }
    });
}

public static  String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens, IKey iKey) {
    final Iterator it = tokens.iterator();
    if (!it.hasNext()) {
        return "";
    }
    final StringBuilder sb = new StringBuilder();
    String key = iKey.getKey(it.next());
    sb.append(key);
    while (it.hasNext()) {
        sb.append(delimiter);
        String key2 = iKey.getKey(it.next());
        sb.append(key2);
    }
    return sb.toString();
}

你可能感兴趣的:(优雅的用符号拼接list中的元素)