myList.add("Apple"); myList.add("Banana"); myList.add("Carrots"); String stringRepresentationOfList = myList.toString(); System.out.println(stringRepresentationOfList);
The output would be our expected:
[Apple, Banana, Carrots]But the hard part is if we want to convert a list to string using a custom separator. In this case, we need a longer code in Java to do the trick. Say for example, we use dash as separator.
String separator = "-"; List<String> myList = new ArrayList<String>(); myList.add("Apple"); myList.add("Banana"); myList.add("Carrots"); StringBuilder sb = new StringBuilder(); for (String item : myList) { if (sb.length() > 0) { sb.append(separator); } sb.append(item); } String stringRepresentationOfList = sb.toString(); System.out.println(stringRepresentationOfList);
This will give the output:
Apple-Banana-Carrots
There is a nice trick in Groovy on how to convert a list to String:
def myList = ["Apple", "Banana", "Carrot"] String stringRepresentationOfList = myList.join("-,") println stringRepresentationOfList;
And this does the trick. Just a one liner and we were able to convert a List to String in Groovy using a custom separator. The output should be the same as above:
Apple-Banana-Carrots