Java: Convert List<Integer> to String

I think you may use simply List.toString() as below:

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]

If you don't want [] in the string, simply use the substring e.g.:

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

Please note: List.toString() uses AbstractCollection#toString method, which converts the list into String as above


With Guava:

String s = Joiner.on(',').join(integerList);

In vanilla Java 8 (streams) you can do

// Given numberList is a List<Integer> of 1,2,3...

String numberString = numberList.stream().map(String::valueOf)
    .collect(Collectors.joining(","));

// numberString here is "1,2,3"

Tags:

Java