Java 集合或数组转变为逗号分隔的字符串的几种方式

首先,创建一个集合

	List list = Lists.newArrayList(null, "bob", "jack");

1、自己编码实现

    public static  String join(List list, String splitStr) {
        if (CollectionUtils.isEmpty(list))
            return "";
        if (list.size() == 1)
            return String.valueOf(list.get(0));
        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;
        for (int i = 0; i < list.size(); i++) {
            if (!isFirst) sb.append(splitStr);
            sb.append(String.valueOf(list.get(i)));
            isFirst = false;
        }
        return sb.toString();
    }

    public static  String join(T[] array, String splitStr) {
        if (ArrayUtils.isEmpty(array))
            return "";
        if (array.length == 1)
            return String.valueOf(array[0]);
        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;
        for (int i = 0; i < array.length; i++) {
            if (!isFirst) sb.append(splitStr);
            sb.append(String.valueOf(array[i]));
            isFirst = false;
        }
        return sb.toString();
    }

输出

	null,bob,jack

2、org.apache.commons.lang3.StringUtils

	System.out.println(StringUtils.join(list.toArray(), ","));

输出

	,bob,jack

3、StringJoiner, JDK1.8+

	StringJoiner sj = new StringJoiner(",");
	list.forEach(e -> sj.add(String.valueOf(e)));
	System.out.println(sj.toString());
	
	// 在连接之前操作字符串, 拼接前缀和后缀
	StringJoiner sj2 = new StringJoiner(",", "START_", "_END");
	list.forEach(e -> sj2.add(String.valueOf(e)));
	System.out.println(sj2.toString());

输出

	null,bob,jack
	START_null,bob,jack_END

4、String.join(), JDK1.8+

	System.out.println(String.join(",", list));

输出

	null,bob,jack

5、Stream, Collectors.joining(), JDK1.8+

	System.out.println(list.stream().collect(Collectors.joining(",")));
	
	// 在连接之前操作字符串, 拼接前缀和后缀
	String str = list.stream().map(e -> {
	   if (e != null) return e.toUpperCase();
	   else return "null";
	}).collect(Collectors.joining(",", "START_", "_END"));
	System.out.println(str);

输出

	null,bob,jack
	START_null,BOB,JACK_END

你可能感兴趣的:(Java)