Java: convert List<String> to a join()d String
To convert a List<String>
to a single string by joining the elements of the list with a separator, you can use the join()
method of the java.util.StringJoiner
class.
Here's an example of how you can use the StringJoiner
class to join the elements of a List<String>
:
import java.util.List;
import java.util.StringJoiner;
List<String> list = List.of("apple", "banana", "cherry");
StringJoiner joiner = new StringJoiner(", ");
for (String s : list) {
joiner.add(s);
}
String joined = joiner.toString();
System.out.println(joined); // apple, banana, cherry
Alternatively, you can use the Collectors.joining()
method of the java.util.stream.Collectors
class to join the elements of a List<String>
using a stream:
import java.util.List;
import java.util.stream.Collectors;
List<String> list = List.of("apple", "banana", "cherry");
String joined = list.stream().collect(Collectors.joining(", "));
System.out.println(joined); // apple, banana, cherry
Both of these examples will produce a string that contains the elements of the List<String>
separated by a comma and a space.