95

Is there a function like join that returns List's data as a string of all the elements, joined by delimiter provided?

 List<String> join; ....
 String join = list.join('+");
 // join == "Elem 1+Elem 2";

or one must use an iterator to manually glue the elements?

EugeneP
  • 11,783
  • 32
  • 96
  • 142

6 Answers6

153

Java 8...

String joined = String.join("+", list);

Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-

gahrae
  • 1,993
  • 1
  • 15
  • 11
  • 3
    Sadly `String.join()` accepts only `Iterable` (apart from varargs) unlike Guava's `Joiner.join()` which accepts `Iterable>`, `Iterator>`, varargs, ... – Venkata Raju Aug 07 '14 at 12:26
  • 7
    Correct - String.join() does not handle arbitrary types. It expects an iterable CharSequence, ie List. If you want to delimit arbitrary types then you need to extract the String value and build the delimited list. This is also a one liner in Java 8: `String joined = iterableOfNonCharSequence.stream().map(object -> object.methodToGetStringValue()).collect(Collectors.joining(","));` – gahrae Aug 08 '14 at 04:46
  • StringJoiner is also a useful class for joining content. Here is an example program showing StringJoiner and Collectors.joining... http://pastebin.com/i2YwJcZy# – gahrae Jul 17 '15 at 18:45
  • native java solutions > all – fIwJlxSzApHEZIl Jul 21 '17 at 23:26
98

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273
  • Of course, creating an utility class is also really easy, if you don't want to use a third-party library for that. But `Apache Commons Lang` provide many usefull methods, that takes care of `null` values... – Romain Linsolas Oct 26 '10 at 08:29
19

Or Joiner from Google Guava.

Joiner joiner = Joiner.on("+");
String join = joiner.join(joinList);
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
nanda
  • 24,458
  • 13
  • 71
  • 90
4

You can use : org.springframework.util.StringUtils;

String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);
Karim Oukara
  • 2,638
  • 8
  • 38
  • 51
3

If you are using Spring you can use StringUtils.join() method which also allows you to specify prefix and suffix.

String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
                "\n", "<value>", "</value>");
marcello
  • 31
  • 1
2

If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.

Alex G
  • 718
  • 1
  • 7
  • 9