美文网首页
优雅的用符号拼接list中的元素

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

作者: gaom明 | 来源:发表于2019-10-10 17:43 被阅读0次

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

public static void main(String[] args) {

    ArrayList<Data> 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<Data>() {
        @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<T> {
    String getKey(T t);
}

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

public static <T> String join(@NonNull CharSequence delimiter, @NonNull Iterable<T> 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中的元素

      本文链接:https://www.haomeiwen.com/subject/zllapctx.html