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);
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);
No it won't work.
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
For example
for (String item : list) {
result += item + " ";
}
Or just use String.join
String.join(" ", list);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With