Java 8 StringJoiner Example

Learn to use StringJoiner class (introduced in Java 8) to join strings in different ways. We can use it to join strings with delimiter, use prefix and/or suffix characters around the result string.

1. StringJoiner example with delimiter, prefix and suffix

Let’s start with one quick example to use StringJoiner to add strings with delimiter comma. In this Java program, we are adding part of this blog name – delimited by comma. We are also using prefix and suffix characters as angular brackets.

StringJoiner joiner = new StringJoiner(",", "[", "]");
		
joiner.add("how");
joiner.add("to");
joiner.add("do");
joiner.add("in");
joiner.add("java");

String result = joiner.toString();

System.out.println(result);

Program output.

[how,to,do,in,java]

2. Java 8 StringJoiner example with delimiter only

In StringJoiner, prefix and suffix are optionals. Only delimiter is mandatory argument.

  1. If we do not provide prefix and suffix to StringJoiner, internally, an empty string is used as prefix and suffix, both.
  2. No argument to StringJoiner can be null. It will result in NullPointerException error.

Given is Java program to join strings with StringJoiner, only using delimiter.

StringJoiner joiner = new StringJoiner("-");
		
joiner.add("how");
joiner.add("to");
joiner.add("do");
joiner.add("in");
joiner.add("java");

String result = joiner.toString();

System.out.println(result);

Program output.

how-to-do-in-java

3. Merge Two StringJoiners

It is possible that two parts of application joined the strings, and now those need to be combined. Use StringJoiner.merge() method to merge two instances of StringJoiner to produce a single result.

When you merge two joiners, this happens –

  1. Content of argument joiner is added to first joiner, on which method is called.
  2. Both joiners persist their delimiters.
  3. Prefix and suffix is used of first joiner on which method is called.

Java program to stringjoiner merge example.

//First Joiner
StringJoiner joiner1 = new StringJoiner(",", "[", "]");
		
joiner1.add("how");
joiner1.add("to");
joiner1.add("do");
joiner1.add("in");
joiner1.add("java");

//Second Joiner
StringJoiner joiner2 = new StringJoiner("-", "{", "}");

joiner2.add("java");
joiner2.add("tutorials");
joiner2.add("blog");

joiner1.merge( joiner2 );

System.out.println( joiner1.toString() );	//Merged content

System.out.println( joiner2.toString() );	//Unchanged

Program output.

[how,to,do,in,java,java-tutorials-blog]
{java-tutorials-blog}

4. Java 8 Stream – Collectors.joining()

Collectors.joining() is designed with a fluent API, and can be used with Java 8 streams.

In Java 8, you can use Collectors.joining() method to join stream of strings (or stream of primitives with their string value). This method internally uses StringJoiner class.

4.1. Join Stream of strings

Java program to join stream of strings in Java 8.

List<String> blogNameParts = Arrays.asList("how", "to", "do", "in", "java");
		
String joinedString = blogNameParts.stream()
								.map(namePart -> namePart)
								.collect(Collectors.joining(",", "[", "]"));

System.out.println(joinedString);

Program output.

[how,to,do,in,java]

4.2. Join stream of primitives

Java program to join stream of integers in Java 8. We didn’t used prefix and suffix this time.

List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9);
		
String joinedString = numbers.stream()
							.map(number -> String.valueOf(number))
							.collect(Collectors.joining(","));

System.out.println(joinedString);

Program output.

1,2,3,4,5,6,7,8,9

5. StringJoiner.setEmptyValue() – Set default value

Use setEmptyValue() method to set any default value in StringJoiner. You can use this default value to see if after computation any element has been added to it, or not.

Please note that before calling setEmptyValue(), default value is "prefix + suffix".

StringJoiner joiner = new StringJoiner(",", "[", "]");

System.out.println(joiner.toString());
		
joiner.setEmptyValue("EMPTY");

System.out.println(joiner.toString());

joiner.add("how");
joiner.add("to");
joiner.add("do");
joiner.add("in");
joiner.add("java");

System.out.println(joiner.toString());

Program output.

[]
EMPTY
[how,to,do,in,java]

6. StringJoiner vs StringBuilder

StringJoiner makes joining strings easy, as compared to StringBuilder.

If you have to join strings from StringBuilder, then you will append each string and delimiter in alternate sequence. And do not forget to remove delimiter appended to last of final string, if it there.

By using, StringJoiner with delimiter in constructor, you only need to focus of Strings to add. Delimiter will be added automatically.

It makes StringJoiner a better way to join strings in Java.

7. Summary

In this Java 8 StringJoiner example, we learned to create StringJoiner in two different ways. First with only delimiter, second with all three parameters – delimiter, prefix and suffix.

We learned to join strings, primitives as well. We saw the use of Collectors.joining() method for collecting stream elements.

Overall, StringJoiner is much like StringBuilder and StringBuffer classes and does not offer any super useful feature. StringJoiner provides efficient formatting of a sequence of strings with separators, but is not suitable for other formatting tasks.

Happy Learning !!

References:

StringJoiner Java Doc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.