可以通过以下步骤实现:
以下是一个示例代码,使用逗号作为内层List的分隔符,分号作为外层List的分隔符:
import java.util.List;
public class ListToString {
public static String convertToString(List<List<String>> list, String innerSeparator, String outerSeparator) {
StringBuilder sb = new StringBuilder();
for (List<String> innerList : list) {
StringBuilder innerSb = new StringBuilder();
for (String str : innerList) {
innerSb.append(str).append(innerSeparator);
}
// 删除最后一个内层List分隔符
if (innerSb.length() > 0) {
innerSb.setLength(innerSb.length() - innerSeparator.length());
}
sb.append(innerSb).append(outerSeparator);
}
// 删除最后一个外层List分隔符
if (sb.length() > 0) {
sb.setLength(sb.length() - outerSeparator.length());
}
return sb.toString();
}
public static void main(String[] args) {
List<List<String>> list = List.of(
List.of("A", "B", "C"),
List.of("D", "E", "F"),
List.of("G", "H", "I")
);
String result = convertToString(list, ",", ";");
System.out.println(result);
}
}
输出结果为:A,B,C;D,E,F;G,H,I
这个方法可以用于将多层嵌套的List<String>连接成一个单个字符串,适用于需要将多个列表数据合并成一个字符串的场景,例如将多个表格的数据拼接成一个CSV文件等。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云