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);
Share:
11,393
user3345791
Author by

user3345791

Updated on June 04, 2022

Comments

  • user3345791
    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
    prasadmadanayake about 9 years
    why separate replace for character ',' you should add ',' to the same regex ex : "[\[\],]"
  • Mohamed Idris
    Mohamed Idris about 9 years
    No, the first replace is for removing [ and ] while the second replace is for replacing "," by " ". Note the difference between "" and " "
  • prasadmadanayake
    prasadmadanayake about 9 years
    yep. missed that. sorry and thanks.