Reputation: 8495
Does anyone know how to strip the brackets off the ends of a resulting string after running a List.toString() operation. Im wondering if there is a build in operation. One that does not involve looping through the string or creating a sub-string of the second and list.size()-1. Some code below. Thanks!
List<Element> elementsBetween = new ArrayList<Element>();
elementBetween.add("some data");
String result = = elementsBetween.toString();
Upvotes: 0
Views: 590
Reputation: 62864
Using Guava, you can do:
List<String> items = Arrays.asList("a","b","c");
String output = Joiner.on(", ").join(items);
System.out.println(output);
which will result in:
a, b, c
You can read more here.
Upvotes: 3
Reputation: 51353
As far as I understand you you want a List of String elements to be represented as:
"element1, element2, element3"
You should use a library like apache commons-lang. E.g. the StringUtils.join(Collection collection, String separator)
List<Element> elementsBetween = new ArrayList<Element>();
elementBetween.add("some data1");
elementBetween.add("some data2");
String joined = StringUtils.join(elementsBetween, ", ");
// joined will be equal to
"some data1, some data2"
Upvotes: 3