简介
在实际开发中我们经常会遇到把集合拼接陈字符串的情况,今天我们使用原生JDK1.8花式玩转字符串拼接。
原理不多,实用程度MAX,我们开始吧。
举例说明
首先我们定义一个公共数据方便后续实例操作
1
| private static String[] names = {"汉服", "中山装", "洛丽塔"};
|
最简单拼接
1 2 3 4
| private static void simpleStringJoin() { String joiner = String.join(",", names); System.out.println(joiner); }
|
输出结果如下:
遍历拼接
1 2 3 4 5 6 7 8
| private static void simpleJoiner() { StringJoiner joiner = new StringJoiner(","); for (String name : names) { joiner.add(name); }
System.out.println(joiner); }
|
输出结果如下:
使用add手动拼接
1 2 3 4 5 6
| private static void simpleAddJoiner() { StringJoiner joiner = new StringJoiner(","); joiner.add("汉服").add("中山装").add("洛丽塔");
System.out.println(joiner); }
|
输出结果如下:
使用lambda循环拼接
1 2 3 4 5 6 7
| private static void simpleListJoiner() { StringJoiner joiner = new StringJoiner(","); List<String> nameLists = Arrays.asList(names); nameLists.forEach(joiner::add);
System.out.println(joiner); }
|
输出结果如下:
数组转集合流处理拼接
1 2 3 4 5 6
| private static void simpleStreamListJoiner() { StringJoiner joiner = Arrays.stream(names) .collect(Collector.of(() -> new StringJoiner(","), StringJoiner::add, StringJoiner::merge));
System.out.println(joiner); }
|
输出结果如下:
数组转集合流处理生成字符串拼接
1 2 3 4 5 6
| private static void simpleStreamStringListJoiner() { String joiner = Arrays.stream(names) .collect(Collector.of(() -> new StringJoiner(","), StringJoiner::add, StringJoiner::merge, StringJoiner::toString));
System.out.println(joiner); }
|
输出结果如下:
使用collect无符号拼接
1 2 3 4 5
| private static void simpleStreamStringListJoining() { String joiner = Arrays.stream(names).collect(Collectors.joining());
System.out.println(joiner); }
|
输出结果如下:
使用collect逗号拼接
1 2 3 4 5
| private static void simpleStreamDelimiterJoining() { String joiner = Arrays.stream(names).collect(Collectors.joining(","));
System.out.println(joiner); }
|
输出结果如下:
普通多条拼接
1 2 3 4 5 6 7
| private static void simpleMultiListJoiner() { StringJoiner joiner = new StringJoiner(",", "我喜欢 ", " !"); List<String> nameLists = Arrays.asList(names); nameLists.forEach(joiner::add);
System.out.println(joiner); }
|
输出结果如下:
使用collect多条拼接
1 2 3 4 5
| private static void simpleStreamMultiJoining() { String joiner = Arrays.stream(names).collect(Collectors.joining(",", "好喜欢 ", "~~"));
System.out.println(joiner); }
|
输出结果如下:
多个join合并拼接
1 2 3 4 5 6 7 8 9 10 11 12 13
| private static void simpleMergeListJoiner() { StringJoiner joiner1 = new StringJoiner(","); List<String> nameLists1 = Arrays.asList(names); nameLists1.forEach(joiner1::add);
StringJoiner joiner2 = new StringJoiner("-"); List<String> nameLists2 = Arrays.asList(names); nameLists2.forEach(joiner2::add);
joiner1.merge(joiner2);
System.out.println(joiner1); }
|
输出结果如下:
结束
有了以上拼接方式,再也不用这拼那截的拼接字符串了。