How to Join a List of Strings with Custom Delimiter, Prefix, and Suffix Using Java 8 Streams

✅ Problem :

How do you join a list of strings with a custom delimiter, prefix, and suffix using Java 8 Streams?

✅ Example:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class JoinStringsCustomDelimiter {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("Apple", "Banana", "Grapes", "Blueberry");

        // Join strings with custom delimiter, prefix, and suffix
        String result = words.stream()
            .collect(Collectors.joining(", ", "[", "]"));

        System.out.println(result);
    }
}

✅ Output:

[Apple, Banana, Grapes, Blueberry]

✅ Explanation:

  1. words.stream(): Converts the list of strings into a Stream of String objects.
  2. Collectors.joining(“, “, “[“, “]”):
    • ", " is the delimiter between elements.
    • "[" is the prefix added at the beginning of the result.
    • "]" is the suffix added at the end of the result.
  3. The result is a single string with all words joined by the delimiter and wrapped in brackets.
  4. The output is printed using System.out.println().

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *