Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Convert List<Integer> to String

Tags:

java

How can I convert List<Integer> to String? E.g. If my List<Integer> contains numbers 1 2 and 3 how can it be converted to String = "1,2,3"? Every help will be appreciated.

like image 888
Martin Avatar asked Nov 02 '12 15:11

Martin


People also ask

How do I turn a list of integers into a string?

The most Pythonic way to convert a list of integers ints to a list of strings is to use the one-liner strings = [str(x) for x in ints] . It iterates over all elements in the list ints using list comprehension and converts each list element x to a string using the str(x) constructor.

Can we convert list to string in Java?

We use the toString() method of the list to convert the list into a string.


1 Answers

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

like image 141
Yogendra Singh Avatar answered Sep 20 '22 08:09

Yogendra Singh