How to convert List to String without commas and brackets
11,393
You can do it easily using replaceAll method like
String result = myList.toString().replaceAll("[\\[\\]]", "").replaceAll(",", " ");
Try the below program. Hope it meets your needs.
List<String> myList = new ArrayList<String>();
myList.add("a");
myList.add("b");
myList.add("c");
String result = myList.toString().replaceAll("[\\[\\]]", "").replaceAll(",", " ");
System.out.println(result);
Author by
user3345791
Updated on June 04, 2022Comments
-
user3345791 almost 2 years
Suppose array list is already created with elements a, b and c in them. but i only want to print the elements without the brackets and commas. would this work?
for(int i=0;i<list.size();i++){ String word = list.get(i); String result = word + " "; } System.out.print(result);
-
prasadmadanayake about 9 yearswhy separate replace for character ',' you should add ',' to the same regex ex : "[\[\],]"
-
Mohamed Idris about 9 yearsNo, the first replace is for removing [ and ] while the second replace is for replacing "," by " ". Note the difference between "" and " "
-
prasadmadanayake about 9 yearsyep. missed that. sorry and thanks.