简体   繁体   中英

Strip brackets from String after list.toString operation

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();

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. Eg 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"

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM