Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Monday, November 8, 2021

Java - Joining Multiple Strings With a Delimiter

1. Overview

In this tutorial, We'll learn how to join the multiple strings with a delimiter in java programming.

Joining strings can be done in several ways with the given separator.

Before java 8, this is solved with the StringBuilder class. But, the same can be solved in 3 ways in java 8 or later.

Let us jump into the example programs on each solution.
Java - Joining Multiple Strings With a Delimiter



2. Java Joining Strings With Delimiter - StringBuilder


StringBuilder is a class that built on the Builder pattern and this is not synchronized.

By using this class, we run the for loop and add the each string and delimiter using append() method.

Look into the below example. Here we are using var-args concept.
package com.javaprogramto.programs.strings.joining;

public class JoiningStringDelimiterExample1 {

	public static void main(String[] args) {

		// input 1
		String output1 = joinStringsWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = joinStringsWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	/**
	 * Gets the joined string for the input strings with a given delimiter
	 * 
	 * @param delimiter
	 * @param strings
	 * @return
	 */
	private static String joinStringsWithDelimiter(String delimiter, String... strings) {

		StringBuilder stringBuilder = new StringBuilder();
		int index = 0;
		for (index = 0; index < strings.length - 1; index++) {

			stringBuilder.append(strings[index]).append(delimiter);
		}

		stringBuilder.append(strings[index]);

		return stringBuilder.toString();
	}

}

Output:
Ouptut 1 : hello-world-welcome-to-java-programs
Ouptut 2 : this**is**second**input

Any no of strings and any delimiter can be passed to this program. And also, StringBuffer can be used in-place of StringBuilder but StringBuffer is slow because of thread safe.

3. Java 8 Joining Strings With Delimiter - StringJoiner


One of the ways in java 8 is using StringJoiner class and this is a string utility class.

StringJoiner class can be used to construct the set of strings with the delimiter.

Look at the below example program.
package com.javaprogramto.programs.strings.joining;

import java.util.StringJoiner;

public class JoiningStringDelimiterExample2 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringJoinerWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringJoinerWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringJoinerWithDelimiter(String delimiter, String... strings) {

		StringJoiner stringJoinder = new StringJoiner(delimiter);
		for (String str : strings) {

			stringJoinder.add(str);
		}

		return stringJoinder.toString();
	}

}

This program produces the same output as above section example.

And alos this supports for adding the suffix and prefix. But these are optional functionality.
StringJoiner stringJoinder = new StringJoiner(delimiter, "!!", "!!");
Output:
Ouptut 1 : !!hello-world-welcome-to-java-programs!!
Ouptut 2 : !!this**is**second**input!!

4. Java 8 Joining Strings With Delimiter - String.join()


String class is added with join() method in java 8. This function reduces the lots of boiler plate coding in the applications now.

String.join() method takes the delimiter and a set of strings.

And alos optionally prefix and suffix also can be passed to join() method.
package com.javaprogramto.programs.strings.joining;

public class JoiningStringDelimiterExample3 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringJoinWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringJoinWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringJoinWithDelimiter(String delimiter, String... strings) {

		return String.join(delimiter, strings);
	}
}

This example also generates the same output.

5. Java 8 Joining Strings With Delimiter - Collectors.joining()


Java 8 stream api is added with very useful method Collectors.joining() method.

Collectors.joining() method should be passed to the collect() method. So that String can be retrieved from joining() output.

Look at the below sample code.
import java.util.Arrays;
import java.util.stream.Collectors;

public class JoiningStringDelimiterExample4 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringCollectorsJoiningWithDelimiter("-", "hello", "world", "welcome", "to", "java",
				"programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringCollectorsJoiningWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringCollectorsJoiningWithDelimiter(String delimiter, String... strings) {

		String output = Arrays.stream(strings).collect(Collectors.joining(delimiter));

		return output;
	}
}

The generated output is same for this example also.

6. Java 8 Joining Strings With Delimiter - Third Party Libraries


Third party api's also provide the support for this functionality from apache commons lang StringUtils.join() and guava Joiner class.
import org.apache.commons.lang3.StringUtils;

public class JoiningStringDelimiterExample5 {

	public static void main(String[] args) {
	// same code as abvoe example
	}

	private static String stringCollectorsJoiningWithDelimiter(String delimiter, String... strings) {

		String output = StringUtils.join(strings, delimiter);

		return output;
	}
}


7. Conclusion


In this article, We've seen how many ways string joining is possible in older java, java 8 and third party apis.

But the String joining strictly discouraged using "+=" operator as below.
String out = "";

for (int i = 0; i < 100000; i++) {
	out += "new value";
}

Because, this code reconstructs many strings with "+=" operation which over kills the memory and prone to performance issues. Finally, this code execution will be much slower than StringBuilder.

No comments:

Post a Comment

Please do not add any spam links in the comments section.