gpt4 book ai didi

Java:将 List 转换为字符串

转载 作者:IT老高 更新时间:2023-10-28 20:54:47 24 4
gpt4 key购买 nike

如何转换 List<Integer> to String ?例如。如果我的 List<Integer>包含数字 1 2 和 3 如何将其转换为 String = "1,2,3"?每一个帮助将不胜感激。

最佳答案

我想你可以简单地使用 List.toString() 如下:

List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);


String listString = intList.toString();
System.out.println(listString); //<- this prints [1, 2, 3]

如果您不想在字符串中出现 [],只需使用子字符串,例如:

   listString = listString.substring(1, listString.length()-1); 
System.out.println(listString); //<- this prints 1, 2, 3

请注意:List.toString() 使用AbstractCollection#toString 方法,如上将列表转换为字符串

关于Java:将 List<Integer> 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13198703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com