Concatenate Strings by Delimiter in an Array

String concatenation is a common operation in Java, often used in formatting data for output, logs, or structured text. In this article, we will learn how to concatenate all strings from an array using a specified delimiter.

Understanding the Problem

Given an array of strings, we need to join them into a single string with a specified delimiter between them.

Example:

Each word from the array is concatenated into a single string, separated by ", ".

Approach to Solve the Problem

  1. Use StringBuilder for Efficient Concatenation:
    • StringBuilder is preferred over String to avoid unnecessary object creation.
  2. Iterate Through the Array:
    • Append each string to StringBuilder.
    • Insert the delimiter between words but not at the end.
  3. Alternative Approach Using Java Streams (Modern & Concise).

Java Program for Concatenating Strings with a Delimiter (Using StringBuilder)

The Java program efficiently concatenates an array of strings using a specified delimiter by leveraging StringBuilder to minimize unnecessary string creation.

package com.javacodepoint.stringarray;

public class ConcatenateStrings {

	// Method to concatenate strings with a delimiter
	public static String concatenateWithDelimiter(String[] words, String delimiter) {
		if (words == null || words.length == 0) {
			return "";
		}

		StringBuilder result = new StringBuilder();

		for (int i = 0; i < words.length; i++) {
			result.append(words[i]); // Append the word

			if (i < words.length - 1) { // Add delimiter except for the last word
				result.append(delimiter);
			}
		}

		return result.toString();
	}

	public static void main(String[] args) {
		// Example array of strings
		String[] words = { "apple", "banana", "grape", "orange" };
		String delimiter = ", ";

		// Concatenate and print the result
		String result = concatenateWithDelimiter(words, delimiter);
		System.out.println("Concatenated String: " + result);
	}
}

Alternative Approach: Using Java Streams

Java provides a built-in method for joining strings with a delimiter using String.join() or Collectors.joining().

Using String.join() (Simple & Readable)

import java.util.Arrays;

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

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

Using Collectors.joining() (Streams API)

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

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

        String result = Arrays.stream(words)
                              .collect(Collectors.joining(delimiter));
        
        System.out.println("Concatenated String: " + result);
    }
}

Time Complexity Analysis

ApproachTime ComplexitySpace Complexity
StringBuilder (Loop)O(N)O(1)
String.join()O(N)O(1)
Streams (Collectors.joining())O(N)O(N)

Conclusion

Concatenating strings with a delimiter is an essential skill in Java. Here we explored the following:

  • StringBuilder for efficiency.
  • Java’s String.join() for simplicity.
  • Streams API for a functional approach.

You can learn the Top 20 string array programs for interview preparation (Click here).

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

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