Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List to String without commas and brackets [closed]

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);
like image 274
user3345791 Avatar asked Nov 16 '25 09:11

user3345791


2 Answers

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);
like image 141
Mohamed Idris Avatar answered Nov 18 '25 04:11

Mohamed Idris


No it won't work.

  • Result needs to be outside the loop
  • You need to append to result rather than overwriting it each time

Fixed.

List<String> list = Arrays.asList("horse", "apples");

String result = "";   //<== needs to be outside the loop
for (int i = 0; i < list.size(); i++) {
    String word = list.get(i);   
    result = result + word + " ";  // <== need to append 
}
System.out.print(result);

Other things to bare in mind

  • Enhanced for loop is easier to use in this case
  • StringBuilder better for massive lists
  • Java 8 String.join() can do this in one line without the trailing space
  • You don't need intermediate variable for word

For example

for (String item : list) {
    result += item + " ";
}

Or just use String.join

String.join(" ", list);
like image 32
Adam Avatar answered Nov 18 '25 04:11

Adam