Joining Multiple Strings in Java using a Delimiter

Introduction

In this guide, we will explore four different approaches to join multiple strings in Java using a delimiter. These methods include using StringBuilder, Java 8 Stream APIs, StringJoiner, and the String.join() method. Each method offers its advantages, and understanding these will help you choose the best approach based on your requirements.

Problem Statement

The task is to join multiple strings into a single string with a specific delimiter. The delimiter will be placed between each of the strings to form a cohesive output.

Example 1:

  • Input: Strings: "apple", "banana", "cherry", Delimiter: ", "
  • Output: "apple, banana, cherry"

Example 2:

  • Input: Strings: "2024", "08", "14", Delimiter: "-"
  • Output: "2024-08-14"

Solution Steps

Approach 1: Using StringBuilder

  1. Initialize Strings: Define the strings you want to join and the delimiter.

  2. Use StringBuilder: Append each string to a StringBuilder, adding the delimiter between strings.

  3. Remove the Trailing Delimiter: Ensure the last delimiter is removed after the final string.

  4. Output the Result: Convert the StringBuilder to a string and print the result.

Java Program for Approach 1

/**
 * Join Multiple Strings in Java using StringBuilder
 * Author: https://www.javaguides.net/
 */
public class StringBuilderExample {

    public static void main(String[] args) {
        String[] words = {"apple", "banana", "cherry"};
        String delimiter = ", ";

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < words.length; i++) {
            sb.append(words[i]);
            if (i < words.length - 1) {
                sb.append(delimiter);
            }
        }

        String result = sb.toString();
        System.out.println("Joined String: " + result);
    }
}

Output for Approach 1

For the input strings "apple", "banana", "cherry" with the delimiter ", ", the output will be:

Joined String: apple, banana, cherry

Approach 2: Using Java 8 Stream APIs

  1. Initialize Strings: Define the strings you want to join and the delimiter.

  2. Use Stream API: Convert the array of strings to a Stream, then use Collectors.joining() to join the strings with the specified delimiter.

  3. Output the Result: Print the joined string.

Java Program for Approach 2

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

/**
 * Join Multiple Strings in Java using Stream APIs
 * Author: https://www.javaguides.net/
 */
public class StreamExample {

    public static void main(String[] args) {
        String[] words = {"2024", "08", "14"};
        String delimiter = "-";

        String result = Arrays.stream(words)
                              .collect(Collectors.joining(delimiter));

        System.out.println("Joined String: " + result);
    }
}

Output for Approach 2

For the input strings "2024", "08", "14" with the delimiter "-", the output will be:

Joined String: 2024-08-14

Approach 3: Using Java 8 StringJoiner

  1. Initialize Strings: Define the strings you want to join and the delimiter.

  2. Use StringJoiner: Create a StringJoiner object with the delimiter, and then add each string to it.

  3. Output the Result: Convert the StringJoiner to a string and print the result.

Java Program for Approach 3

import java.util.StringJoiner;

/**
 * Join Multiple Strings in Java using StringJoiner
 * Author: https://www.javaguides.net/
 */
public class StringJoinerExample {

    public static void main(String[] args) {
        String[] words = {"one", "two", "three"};
        String delimiter = ", ";

        StringJoiner joiner = new StringJoiner(delimiter);

        for (String word : words) {
            joiner.add(word);
        }

        String result = joiner.toString();
        System.out.println("Joined String: " + result);
    }
}

Output for Approach 3

For the input strings "one", "two", "three" with the delimiter ", ", the output will be:

Joined String: one, two, three

Approach 4: Using String.join() Method

  1. Initialize Strings: Define the strings you want to join and the delimiter.

  2. Use String.join(): Pass the delimiter and the array of strings to String.join() to join them.

  3. Output the Result: Print the joined string.

Java Program for Approach 4

/**
 * Join Multiple Strings in Java using String.join()
 * Author: https://www.javaguides.net/
 */
public class StringJoinMethodExample {

    public static void main(String[] args) {
        String[] words = {"hello", "world", "Java"};
        String delimiter = " ";

        String result = String.join(delimiter, words);
        System.out.println("Joined String: " + result);
    }
}

Output for Approach 4

For the input strings "hello", "world", "Java" with the delimiter " ", the output will be:

Joined String: hello world Java

Conclusion

These four approaches provide flexible ways to join multiple strings in Java using a delimiter. Depending on your specific requirements and the Java version you are using, you can choose the method that best fits your needs. The StringBuilder approach is efficient for cases where you have many strings to join, while the Java 8 Stream API and StringJoiner provide more concise and modern alternatives. The String.join() method is the simplest and most straightforward for joining strings with a delimiter.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare