JDK8 | 字符串收集器 Collectors.joining()

JDK8的流收集器Collectors.joining

支持灵活的参数配置,可以指定字符串连接时的分隔符,前缀和后缀,可选用。用于拼接字符串,更方便好用。

例:

final String[] strs= {
    
    "a", "b", "c"};
Stream<String> stream = Stream.of(strs);
 
// 拼接成 [a, b, c] 形式
String res1 = stream.collect(Collectors.joining(", ", "[", "]"));
// 拼接成 a | b | c 形式
String res2 = stream.collect(Collectors.joining(" | ", "", ""));
// 拼接成 a - b - c] 形式
String res3 = stream.collect(Collectors.joining(" - ", "", ""));

猜你喜欢

转载自blog.csdn.net/qq_25112523/article/details/109197898
今日推荐