StringJoiner
215字小于1分钟
2024-08-08
用分隔符拼接数组的需求很常见,所以 Java
标准库还提供了一个 StringJoiner
来干这个事
拼接数组
例如:逗号隔开方式拼接数组
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
StringJoiner stringJoiner = new StringJoiner(",");
for (String str : list) {
stringJoiner.add(str);
}
System.out.println(stringJoiner.toString()); // A,B,C,D
}
例如:特定开头和结尾拼接数组
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
StringJoiner stringJoiner = new StringJoiner(",","start "," end");
for (String str : list) {
stringJoiner.add(str);
}
System.out.println(stringJoiner.toString()); // start A,B,C,D end
}
String.join()
String
还提供了一个静态方法 join()
,这个方法在内部使用了 StringJoiner
来拼接字符串,在不需要指定"开头"和"结尾"的时候,用 String.join()
更方便
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
String str = String.join(",", list);
System.out.println(str); // A,B,C,D
}