All of the below methods produce the same result of joining the elements of the List into a single String with space as a delimiter.
Using Collectors.joining:
In Java, you can use the Collectors.joining()
method to join the elements of a List into a single String. Here’s an example:
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ListToStringExample { public static void main(String[] args) { List<String> list = Arrays.asList("Hello", "world", "!", "How", "are", "you", "?"); String result = list.stream() .collect(Collectors.joining(",")); System.out.println(result); } }
Using String.join()
import java.util.Arrays; import java.util.List; public class ListToStringExample { public static void main(String[] args) { List<String> list = Arrays.asList("Hello", "world", "!", "How", "are", "you", "?"); String result = String.join(",", list); System.out.println(result); // Output: Hello,world, !, How, are, you, ? } }
Using a StringBuilder
import java.util.Arrays; import java.util.List; public class ListToStringExample { public static void main(String[] args) { List<String> list = Arrays.asList("Hello", "world", "!", "How", "are", "you", "?"); StringBuilder sb = new StringBuilder(); for (String s : list) { sb.append(s).append(","); } String result = sb.toString().trim(); System.out.println(result); // Output: Hello world ! How are you ? } }