In Java 8 or later:
String listString = String.join(", ", list);
In case the list is not of type String, a joining collector can be used:
String listString = list.stream().map(Object::toString)
.collect(Collectors.joining(", "));
Answer from Vitalii Fedorenko on Stack OverflowIn Java 8 or later:
String listString = String.join(", ", list);
In case the list is not of type String, a joining collector can be used:
String listString = list.stream().map(Object::toString)
.collect(Collectors.joining(", "));
If you happen to be doing this on Android, there is a nice utility for this called TextUtils which has a .join(String delimiter, Iterable) method.
List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
String joined = TextUtils.join(", ", list);
Obviously not much use outside of Android, but figured I'd add it to this thread...
Using Java 8 you can do this in a very clean way:
String.join(delimiter, elements);
This works in three ways:
1) directly specifying the elements
String joined1 = String.join(",", "a", "b", "c");
2) using arrays
String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);
3) using iterables
List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);
If you're on Android you can TextUtils.join(delimiter, tokens)
You may use a StringJoiner for that solution.
List<String> mainList = new ArrayList<>(); //The one to contain all Strings from yourList
List<String> yourList = Arrays.asList("Hey", "how", "are", "you"); //The list of Strings
StringJoiner joiner = new StringJoiner(" "); //Space as delimiter, strings will be separated with spaces
for (String s : yourlist) {
joiner.add(s);
}
mainList.add(joiner.toString()); //Add the new concatenated String to your list, in a single string
Java 8 added a StringJoiner class which does exactly what you want (the following code is in Java 9):
List<String> list = List.of("hey", "how", "are", "you");
StringJoiner joiner = new StringJoiner(" ");
list.forEach(str -> joiner.add(str));
System.out.println(joiner.toString()); // hey how are you
// and if you want the final result to be in a list
// Java 9:
list = List.of(joiner.toString());
// anything before Java 9
list = Arrays.asList(joiner.toString());
Another (simpler) way to do it (since Java 8):
String.join(" ", list)