Java:将List 转换为String
如何将List to String
转换List to String
? 例如,如果我的List
包含数字1 2和3,如何将它转换为String =“1,2,3”? 我们将不胜感激。
一种方法是:
Iterate
列表,将每个项添加到StringBuffer
(或) StringBuilder
并在结尾处执行toString()
。
例:
StringBuilder strbul = new StringBuilder(); Iterator iter = list.iterator(); while(iter.hasNext()) { strbul.append(iter.next()); if(iter.hasNext()){ strbul.append(","); } } strbul.toString();
用番石榴 :
String s = Joiner.on(',').join(integerList);
我想你可以使用如下的List.toString()
:
List intList = new ArrayList (); 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
方法,该方法将列表转换为String,如上所述