1

加入多个字符串参数

String joinedString = String.join(", ", "How", "To", "Do", "In", "Java");
System.out.println(joinedString);
 
Output:
 
How, To, Do, In, Java

加入数组或字符串列表

List<String> strList = Arrays.asList("How", "To", "Do", "In", "Java");
         
String joinedString = String.join(", ", strList);
 
System.out.println(joinedString);
 
Output:
 
How, To, Do, In, Java

格式化输出


使用StringJoiner类,我们可以生成连接字符串的格式化输出。这在使用lambda收集器时特别有用。

StringJoiner joiner = new StringJoiner(", ", "[", "]");
 
joiner.add("How")
        .add("To")
        .add("Do")
        .add("In")
        .add("Java");
 
Output:
 
[How, To, Do, In, Java]

带有Collectors.joining()的字符串的字符串列表

List<String> numbers = Arrays.asList("How", "To", "Do", "In", "Java");
 
String joinedString =   numbers
                        .stream()
                        .collect(Collectors.joining(", ","[","]"));
 
System.out.println(joinedString);
 
Output:
 
[How, To, Do, In, Java]


我组建了一个技术交流群,里边会有技术大佬一起交流学习,共同成长。需要的朋友可以加我微信(微信ID:yonglun_1994),拉你进群,并有学习大礼包相送。

蜗牛.jpeg


蜗牛互联网
354 声望19 粉丝