You can use Java 8 Streams with Collectors.joining() to join a list of strings with a specified prefix, suffix, and delimiter.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class JoinStrings {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry");
String result = words.stream()
.collect(Collectors.joining(",", "[", "]")); // Prefix: [, Suffix: ], Delimiter: ,
System.out.println(result);
}
}
Output:
[apple,banana,cherry]
Explanation:
stream()→ Converts the list into a Stream.Collectors.joining(",", "[", "]"):","→ Delimiter between elements."["→ Prefix before the first element."]"→ Suffix after the last element.
collect(Collectors.joining(...))→ Joins the elements into a single string.
