HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / String / Java 8 StringJoiner Example

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces