java list转逗号隔开的字符串
时间: 2024-01-11 18:39:29 浏览: 147
你可以使用Java的StringJoiner类或者StringBuilder来实现将List转换为逗号分隔的字符串。
使用StringJoiner类的示例代码如下:
```java
import java.util.List;
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
List<String> list = List.of("apple", "banana", "orange");
StringJoiner joiner = new StringJoiner(",");
for (String item : list) {
joiner.add(item);
}
String result = joiner.toString();
System.out.println(result);
}
}
```
使用StringBuilder的示例代码如下:
```java
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = List.of("apple", "banana", "orange");
StringBuilder builder = new StringBuilder();
for (String item : list) {
builder.append(item).append(",");
}
String result = builder.toString();
if (result.endsWith(",")) {
result = result.substring(0, result.length() - 1);
}
System.out.println(result);
}
}
```
这两种方法都可以将List中的元素用逗号连接起来,得到一个逗号分隔的字符串。
阅读全文